Go 1.10 was released today and an addition to the core library encoding/json
package caught my eye
func (dec *Decoder) DisallowUnknownFields()
DisallowUnknownFields causes the Decoder to return an error when the destination is a struct and the input contains object keys which do not match any non-ignored, exported fields in the destination.
The first usecase I thought of was in a web service; DisallowUnknownFields
could
be used to reject requests with undefined attributes in the request body. Here's a quick PoC
package main
import (
"encoding/json"
"fmt"
"log"
"net/http"
)
func main() {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
var user struct {
Name string `json:"name"`
}
decoder := json.NewDecoder(r.Body)
decoder.DisallowUnknownFields()
if err := decoder.Decode(&user); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
fmt.Fprintf(w, "hi %s!", user.Name)
})
log.Fatal(http.ListenAndServe(":8080", nil))
}
Requests with the proper fields are unaffected
curl -d '{"name": "susan"}' localhost:8080
hi susan!
Requests with undefined fields raise an error
curl -d '{"name": "susan", "age": 25}' localhost:8080
json: unknown field "age"
Hi thanks for this code, just one question: if add another unknown field to json, it just gave me the first unknown field how can i get all the unknown fields errors?