これは信じられないほどハックに思えます.Goにはこれよりも優れた設計のライブラリがあると考えていましたが、JSONデータのPOSTリクエストを処理するGoの例を見つけることができません. それらはすべてフォーム POST です。
リクエストの例を次に示します。curl -X POST -d "{\"test\": \"that\"}" http://localhost:8082/test
ログが埋め込まれたコードは次のとおりです。
package main
import (
"encoding/json"
"log"
"net/http"
)
type test_struct struct {
Test string
}
func test(rw http.ResponseWriter, req *http.Request) {
req.ParseForm()
log.Println(req.Form)
//LOG: map[{"test": "that"}:[]]
var t test_struct
for key, _ := range req.Form {
log.Println(key)
//LOG: {"test": "that"}
err := json.Unmarshal([]byte(key), &t)
if err != nil {
log.Println(err.Error())
}
}
log.Println(t.Test)
//LOG: that
}
func main() {
http.HandleFunc("/test", test)
log.Fatal(http.ListenAndServe(":8082", nil))
}
もっと良い方法があるはずですよね?私はベストプラクティスが何であるかを見つけることに困惑しています。
(Go は検索エンジンでは Golang としても知られており、他の人が見つけられるようにここで言及しています。)