Golang 使用响应中的正文更改 HTTP 响应状态代码 201

Hel*_*llo -1 http httpresponse go http-status-code-404

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

cre*_*ack 7

我刚刚尝试过,它似乎有效。

你有损坏代码的样本吗?

简单示例:(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))
}
Run Code Online (Sandbox Code Playgroud)

然后

$> 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"}
Run Code Online (Sandbox Code Playgroud)