[Go]POSTされたJSONを受け取るHTTPサーバーでエラーが発生します。
##事象
Go言語でPOSTされたjsonを受け取るHTTPサーバーを作りました。
コマンドプロンプトからcurlしたところ、エラーが出てしまいます。
json.Unmarshalのところで発生しているようです。
解決方法をご存知でしたらどうかご教授くださいませ。
console
1&{0xc0000e2140 <nil> <nil> false true {0 0} false false false 0x6182a0}[0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0 0] 2'{hoge:hogehoge}' 3invalid character '\'' looking for beginning of value
cmd
1curl -v -X POST -H "Content-Type: application/json" -d '{"hoge":"hogehoge"}' http://localhost:8080
Go
1package main 2 3import ( 4 "encoding/json" 5 "fmt" 6 "io" 7 "net/http" 8 "strconv" 9) 10 11func jsonPostHandler(writer http.ResponseWriter, request *http.Request) { 12 fmt.Print(request.Body) 13 if request.Method == "GET" { 14 fmt.Println("Bad Method") 15 writer.WriteHeader(http.StatusBadRequest) 16 return 17 } 18 19 if request.Header.Get("Content-Type") != "application/json" { 20 fmt.Println("Not json") 21 writer.WriteHeader(http.StatusBadRequest) 22 return 23 } 24 25 length, err := strconv.Atoi(request.Header.Get("Content-Length")) 26 if err != nil { 27 writer.WriteHeader(http.StatusBadRequest) 28 return 29 } 30 31 body := make([]byte, length) 32 fmt.Println(body) 33 bdy, err := request.Body.Read(body) 34 if err != nil && err != io.EOF { 35 fmt.Println("ERROR") 36 writer.WriteHeader(http.StatusBadRequest) 37 return 38 } 39 40 var jsonBody map[string]interface{} 41 err = json.Unmarshal(body[:bdy], &jsonBody) 42 fmt.Println(string(body[:bdy])) 43 if err != nil { 44 fmt.Println(err) 45 writer.WriteHeader(http.StatusInternalServerError) 46 return 47 } 48 fmt.Printf("%v", jsonBody) 49 writer.WriteHeader(http.StatusOK) 50 51} 52 53func main() { 54 http.HandleFunc("/", jsonPostHandler) 55 http.ListenAndServe(":8080", nil) 56} 57
###環境
Windows10
回答1件
あなたの回答
tips
プレビュー
バッドをするには、ログインかつ
こちらの条件を満たす必要があります。