How do I set the response status code to 201 while including a JSON object in the response body? I can't seem to perform both of these at once -- either I return a 200 with a message body, or a 201 without one.
I just tried and it seems to work.
Would you have a sample of broken code?
Simple example: (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))
}
Then
$> 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"}