json形式でpostされたhttp requestを処理するサンプル。
今回はpostするjsonのデータ構造を特に決めていないのでパース結果をmap[string]interface{}に保存。
srv.go
package main
import (
"net/http"
"io"
"encoding/json"
"fmt"
"strconv"
)
func dumpJsonRequestHandlerFunc(w http.ResponseWriter, req *http.Request){
//Validate request
if req.Method != "POST" {
w.WriteHeader(http.StatusBadRequest)
return
}
if req.Header.Get("Content-Type") != "application/json" {
w.WriteHeader(http.StatusBadRequest)
return
}
//To allocate slice for request body
length, err := strconv.Atoi(req.Header.Get("Content-Length"))
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
//Read body data to parse json
body := make([]byte, length)
length, err = req.Body.Read(body)
if err != nil && err != io.EOF {
w.WriteHeader(http.StatusInternalServerError)
return
}
//parse json
var jsonBody map[string]interface{}
err = json.Unmarshal(body[:length], &jsonBody)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
return
}
fmt.Printf("%v\n", jsonBody)
w.WriteHeader(http.StatusOK)
}
func main(){
http.HandleFunc("/json", dumpJsonRequestHandlerFunc)
http.ListenAndServe(":8080", nil)
}
json形式のリクエストを受けるサーバを立ち上げる
$go run srv.go
json形式のリクエストをcurlで叩く
$curl -v -H "Content-Type: application/json" -X POST -d '{"integer":1,"string":"xyz", "object": { "element": 1 } , "array": [1, 2, 3]}' http://localhost:8080/json