在Go的HTTP响应中返回JSON主体的教程

2,091 阅读2分钟

概述

net/http包中ResponseWriter接口的Write方法可以用来设置HTTP响应中的JSON主体。

在GO中,响应是由ResponseWriter接口表示的。 以下是该接口的链接 --

golang.org/pkg/net/htt…

ResponseWriter接口被HTTP处理程序用来构建一个HTTP响应。它提供了三个函数来设置响应参数

  • Header - 用于编写响应头

  • Write([]byte) - 用于写入响应的正文

  • WriteHeader(statusCode int) - 用于写入http状态码

Write函数可以用来设置响应体。它需要一个字节片作为输入。此外,还有一个Header 函数。这个函数可以用来使用Content-Type头来设置响应体的内容类型。例如,在JSON响应体的情况下,我们需要将Content-Type头设置为**"application/json"。**

w.Header().Set("Content-Type", "application/json")

另外,注意WriteHeader 函数可以用来设置响应的HTTP状态代码。

例子

让我们看看发送HTTP状态代码和JSON响应体的例子

以下是相同的程序

package main

import (
	"encoding/json"
	"log"
	"net/http"
)

func main() {
	handler := http.HandlerFunc(handleRequest)
	http.Handle("/example", handler)
	http.ListenAndServe(":8080", nil)
}

func handleRequest(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusCreated)
	w.Header().Set("Content-Type", "application/json")
	resp := make(map[string]string)
	resp["message"] = "Status Created"
	jsonResp, err := json.Marshal(resp)
	if err != nil {
		log.Fatalf("Error happened in JSON marshal. Err: %s", err)
	}
	w.Write(jsonResp)
	return
}

在上面的程序中,我们是这样创建一个JSON响应的。我们使用json.Marshal函数将map[string]字符串转换成json字节。

resp := make(map[string]string)
resp["message"] = "Status Created"
jsonResp, err := json.Marshal(resp)
if err != nil {
	log.Fatalf("Error happened in JSON marshal. Err: %s", err)
}
w.Write(jsonResp)

然后,它使用Write函数来返回JSON响应体。上述代码在响应中返回以下JSON响应体

{"message":"Status Created"}

另外,我们使用WriteHeader函数来指定201 http状态代码。

运行上述程序。它将在你的本地机器上启动一个8080端口的服务器。现在对服务器进行下面的curl调用

curl -v -X POST http://localhost:8080/example

下面将是输出结果

* Connected to localhost (::1) port 8080 (#0)
> POST /example HTTP/1.1
> Host: localhost:8080
> User-Agent: curl/7.54.0
> Accept: */*
> 
< HTTP/1.1 201 Created
< Date: Sat, 10 Jul 2021 10:40:33 GMT
< Content-Length: 28
< Content-Type: text/plain; charset=utf-8
< 
* Connection #0 to host localhost left intact
{"message":"Status Created"}

你可以从输出中看到,它将正确地返回201状态代码和JSON主体。