JSON Request data

Celerity can extract data from JSON data sent in the request. Data can be extracted as single values or all at once and mapped into a struct.

Extracting data into structures

The handler context provides an Extract function that will fill a structure with values from the request body. Any values preset in the structure will be matched with a value present in the JSON payload. If a value is present in the structure, and not omitted via json annotation, an error will be returned.

Nested structures can also be filled. They just need to match the structure given in the JSON payload.

func myHandler(c celerity.Context) celerity.Response {
    var req := struct {
        FirstName string `json:"firstName"`
        LastName string `json:"lastName"`
        Age int `json:"age"`
        Active bool `json:'active"`
    }
    if err := c.Extract(&req); err != nil {
        return c.E(400, err)
    }
    processUpdate(&req)
    c.R(req)
}

Extracting single values

Its often useful to extract a single, or a few, pieces out of the JSON sent in the request body. A request may only have a value or two you care about. Alternatively, you may be extracting into an existing structure, but still need another sent value that isn’t available in that struct. The example below shows this use case.

type User struct {
        FirstName string `json:"firstName"`
  LastName  string `json:"lastName"`
Age       int `json:"age"`
  Active    bool `json:'active"`
}

func myHandler(c celerity.Context) celerity.Response {
        if err := c.Extract(&user); err != nil {
                return c.E(400, err)
        }
        clearPassword := c.ExtractValue("password").String()
        user.PasswordHash := hashPassword(clearPassword)       
        c.R(req)
}
last modified Thursday, June 21, 2018
Previous in Guides
Basic Routing
Setting up routes and scopes
Next in Guides
Getting Started
A quick setup guide to get a server running
Celerity is maintained by 5Sigma. Source code is available at Github.