package main
import (
"encoding/json"
"fmt"
"net/http"
)
type Person struct {
Name string
Age int
}
func main() {
http.HandleFunc("POST /person", func(w http.ResponseWriter, r *http.Request) {
var p Person
if err := json.NewDecoder(r.Body).Decode(&p); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "Person: %+v", p)
})
if err := http.ListenAndServe(":3000", nil); err != nil {
panic(err)
}
}
$ curl localhost:3000/person -id "invalide body"
HTTP/1.1 400 Bad Request
Content-Type: text/plain; charset=utf-8
X-Content-Type-Options: nosniff
Date: Sat, 26 Oct 2024 05:24:40 GMT
Content-Length: 53
invalid character 'i' looking for beginning of value