Quindi ho il seguente, che sembra incredibilmente hacky, 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 un POST richiesta di dati JSON. Sono tutti moduli POST.Gestione di JSON Post Request in Go
Ecco un esempio di richiesta: curl -X POST -d "{\"test\": \"that\"}" http://localhost:8082/test
E qui è il codice, con i registri 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))
}
Ci
ha avuto modo di essere un modo migliore, giusto? Sono solo perplesso nel trovare quale potrebbe essere la migliore pratica.
(Go è anche conosciuto come Golang ai motori di ricerca, e di cui qui in modo che altri possano trovarla.)
se si utilizza 'curl -X POST -H 'Content-Type: application/json' -d" {\ "test \": \ "that \"} "', quindi 'req.Form [" test " ] 'dovrebbe restituire' "che" ' – Vinicius
@Vinicius ci sono prove di questo? – diraria