-1
在响应正文中包含JSON对象时,如何将响应状态代码设置为201?我似乎无法同时执行这两个 - 无论是我回复一个200消息正文,或201没有一个。Golang在响应中更改HTTP响应状态代码201与正文
在响应正文中包含JSON对象时,如何将响应状态代码设置为201?我似乎无法同时执行这两个 - 无论是我回复一个200消息正文,或201没有一个。Golang在响应中更改HTTP响应状态代码201与正文
我刚刚尝试过,它似乎工作。
你会有一个破碎的代码样本?
简单的例子:(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"}
你能提供您所使用的代码是不工作? – Adrian