Skip to content
Tutorials Center
My learning

Topics

Lesson 11 of 39 ยท Binding and Validation

Binding JSON and Forms in Gin

Turn request bodies into Go structs with ShouldBindJSON and ShouldBind, learn the json and form struct tags, the difference between Bind and ShouldBind, and test decoding with runnable stand-ins.

Handlers rarely care about raw bytes. They want a CreateBookInput struct with a title, an author and a price. Binding is the step that reads the request body (JSON, an HTML form, XML...) and fills such a struct for you. Gin's binding layer sits on top of the standard library decoders and adds one thing the standard library lacks: validation rules in struct tags, which the next lessons cover in depth (validation rules).

This lesson is about the first half: getting data in. If you have not seen how handlers read the URL, read Path and Query Parameters first, and see HTTP Status Codes and Error Responses for what to send when binding fails.

Gin itself does not run on this site. Gin snippets are read-only, and each concept has a runnable Go stand-in using encoding/json and net/http, which is what Gin uses underneath.

Define an input struct

Bindings work on struct fields. The tag names which request field feeds which struct field:

Go
type CreateBook struct {
	Title  string   `json:"title"`
	Author string   `json:"author"`
	Price  float64  `json:"price"`
	Tags   []string `json:"tags"`
}

Only exported fields (capitalized) are filled. Create a separate input struct for each operation instead of reusing your database model: a client must not be able to set ID, CreatedAt or IsAdmin just because the model has those fields. This mistake is known as mass assignment.

ShouldBindJSON

Go
func createBook(c *gin.Context) {
	var in CreateBook
	if err := c.ShouldBindJSON(&in); err != nil {
		c.JSON(http.StatusBadRequest, gin.H{"error": err.Error()})
		return
	}
	c.JSON(http.StatusCreated, gin.H{"title": in.Title, "price": in.Price})
}

ShouldBindJSON reads the body, decodes it with encoding/json and runs validation. When it fails you get an error and you decide the response. That is the key difference between the two families of binding methods:

Method On failure
ShouldBind... Returns the error; you write the response
Bind... / MustBindWith Writes a 400 itself and aborts the chain with a content-type header already sent

Prefer ShouldBind.... Bind removes your chance to send your own error format, and after it writes the 400 you cannot change the status code.

A body can be read only once. If two bindings must read the same JSON (rare), use c.ShouldBindBodyWith(&obj, binding.JSON), which caches the body in the context.

Forms and ShouldBind

HTML forms send application/x-www-form-urlencoded or multipart/form-data. The tag is form:

Go
type Signup struct {
	Email    string `form:"email"`
	Password string `form:"password"`
	Newsletter bool `form:"newsletter"`
}

r.POST("/signup", func(c *gin.Context) {
	var in Signup
	if err := c.ShouldBind(&in); err != nil {
		c.String(http.StatusBadRequest, "bad form: %v", err)
		return
	}
	c.String(http.StatusOK, "welcome %s", in.Email)
})

ShouldBind looks at the request's Content-Type and the method: for a POST with application/json it uses the JSON binder, with a form content type it uses the form binder, and for GET it reads the query string. When you know the format, call the specific method (ShouldBindJSON, ShouldBindQuery, ShouldBindXML...) to avoid surprises. Query and URI binding get their own lesson: Binding Query, URI and Headers.

Checkboxes deserve a note: an unchecked box is not sent at all, so a bool field simply stays false. A checked box sends on by default, which form binding turns into true.

Struct tags and types

You can put several tags on a field so that one struct serves JSON and forms:

Go
type Review struct {
	Stars   int      `json:"stars"   form:"stars"`
	Comment string   `json:"comment" form:"comment"`
	Tags    []string `json:"tags"    form:"tags"`
}

For forms, repeated keys (tags=go&tags=web) fill slices. Gin also converts text to the field type: integers, floats, booleans and time.Time (use time_format:"2006-01-02" on the tag to choose the layout).

With JSON, the standard rules apply:

  • Missing keys leave the field at its zero value, so Price is 0 both when omitted and when sent as 0. Use a pointer (*float64) when you must tell "absent" from "zero".
  • Unknown keys are ignored by default. Gin can reject them: set binding.EnableDecoderDisallowUnknownFields = true once at startup.
  • A wrong type ("price": "free") is an error.
  • Numbers go into float64 when the target is any, which loses precision above 2^53. Call binding.EnableDecoderUseNumber = true if you pass large IDs through any fields.

Stand-in: JSON decoding the Gin way

Here is what happens inside ShouldBindJSON, with strict unknown-field checking turned on. Each case prints either the decoded struct or the error message you would hand back to the client.

Go Stand-in: decoding JSON into a struct

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

Notice how a pointer lets you tell price missing from price: 0, how the unknown field isAdmin is rejected, and how truncated JSON gives an unexpected EOF error. Gin's error text is similar; for validation rules it adds messages of its own.

Stand-in: decoding a form

Forms use url.Values, a map from key to a slice of strings. Gin's form binder does the conversion that the next stand-in does by hand for three fields.

Go Stand-in: filling a struct from form values

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with bufio.Scanner or fmt.Scan), it gets the next line from this box.

The second form shows zero values for everything the browser did not send (an unchecked checkbox is simply absent), and the third shows a conversion error for a non-numeric age.

Responding to binding errors

Binding errors are the client's fault, so they map to 400 (or 422 for validation failures, see the next lessons). Never return a 500 for bad input. A tidy handler looks like this:

Go
var in CreateBook
if err := c.ShouldBindJSON(&in); err != nil {
	fail(c, http.StatusBadRequest, "bad_request", "invalid JSON body")
	return
}

Showing err.Error() directly is fine while developing, but production APIs usually return a friendlier, structured list. Custom Validators and Friendly Error Messages builds that.

Check your understanding

Quick check ยท 5 questions

of 5 answered You scored / 5 ยท perfect!

  1. 1. Which method should you prefer when you want to send your own JSON error on bad input?

    ShouldBind... returns the error and leaves the response to you. Bind... writes a 400 itself.
  2. 2. Which struct tag feeds a field from an HTML form value?

    The form tag is used for urlencoded and multipart form data (and for the query string with ShouldBindQuery).
  3. 3. How can a JSON handler tell an omitted price from a price of 0?

    A pointer stays nil when the key is missing, but points to 0 when the client sent 0.
  4. 4. Why use a separate input struct instead of binding straight into the database model?

    A model usually contains fields the client must not control. An input struct exposes only what is allowed.
  5. 5. What happens to an unchecked HTML checkbox on submit?

    Browsers omit unchecked checkboxes from the submitted form.

Summary

  • Binding fills a struct from the request body; use one input struct per operation.
  • ShouldBindJSON and ShouldBind return errors for you to handle; Bind... replies 400 by itself, so prefer ShouldBind....
  • Tags choose the source: json, form, and later uri, header.
  • Missing keys give zero values; use pointers to detect absence. Unknown JSON keys can be rejected globally.
  • Binding errors are client errors (400/422), never 500.

Next: Binding Query, URI and Headers reads the rest of the request into structs.