Skip to content

Instantly share code, notes, and snippets.

@bndw
Last active May 20, 2023 02:32
Show Gist options
  • Save bndw/a95e49c8bb5581aa4685d289ec9a3aeb to your computer and use it in GitHub Desktop.
Save bndw/a95e49c8bb5581aa4685d289ec9a3aeb to your computer and use it in GitHub Desktop.
go 1.10 encoding/json Decoder.DisallowUnknownFields

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.

Godoc

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"
@FernandoIV
Copy link

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?

@Sehssoft
Copy link

``

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment