Golang在响应中使用Body更改HTTP响应状态代码201

时间:2017-05-25 00:16:41

标签: http go http-status-code-404 httpresponse

如何在响应正文中包含JSON对象时将响应状态代码设置为201?我似乎无法同时执行这两个 - 要么我返回带有消息体的200,要么返回没有消息体的201.

1 个答案:

答案 0 :(得分:2)

我刚试过,似乎有效。

您是否有破损代码的样本?

简单示例:(https://play.golang.org/p/xg8lGNofze

package main

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

func testHdlr(w http.ResponseWriter, req *http.Request) {
    m := map[string]string{
        "foo": "bar",
    }
    w.Header().Add("Content-Type", "application/json")
    w.WriteHeader(http.StatusCreated)
    _ = json.NewEncoder(w).Encode(m)
}

func main() {
    http.HandleFunc("/", testHdlr)
    log.Fatal(http.ListenAndServe(":8080", nil))
}

然后

$> curl -v http://localhost:8080
[...]
< HTTP/1.1 201 Created
< Date: Thu, 25 May 2017 00:54:15 GMT
< Content-Length: 14
< Content-Type: application/json
< 
{ [14 bytes data]
* Curl_http_done: called premature == 0

100    14  100    14    0     0   2831      0 --:--:-- --:--:-- --:--:--  3500
* Connection #0 to host localhost left intact
{"foo":"bar"}