Quindi ho il seguente, che sembra incredibilmente confuso, e ho pensato a me stesso che Go ha librerie progettate meglio di così, ma non riesco a trovare un esempio di Go che gestisce una richiesta POST di dati JSON. Sono tutti post POST.
Ecco una richiesta di esempio: curl -X POST -d "{\"test\": \"that\"}" http://localhost:8082/test
Ed ecco il codice, con i log incorporati:
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))
}
Deve esserci un modo migliore, giusto? Sono solo perplesso nel trovare quale potrebbe essere la migliore pratica.
(Go è anche noto come Golang per i motori di ricerca, e menzionato qui in modo che altri possano trovarlo.)
curl -X POST -H 'Content-Type: application/json' -d "{\"test\": \"that\"}"
, allorareq.Form["test"]
dovrebbe tornare"that"