-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