Documentation ¶
Overview ¶
Package dynjson allow APIs to return only fields selected by the API client:
GET https://api.example.com/v1/foos [{"id":1,foo":1,"bar":2,"baz":3}] GET https://api.example.com/v1/foos?select=foo [{"foo":1}] GET https://api.example.com/v1/foos/1?select=foo {"foo":1}
dynjson mimicks the original struct using the original types and json tags. The field order is the same as the select parameters.
Index ¶
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func FieldsFromRequest ¶ added in v0.2.0
FieldsFromRequest returns the list of fields requested from a http.Request.
Without opt or with OptionMultipleFields, the expected format is: http://api.example.com/endpoint?select=foo&select=bar
With OptionCommaList, the expected format is: http://api.example.com/endpoint?select=foo,bar
Types ¶
type Formatter ¶
type Formatter struct {
// contains filtered or unexported fields
}
Formatter is a dynamic API format formatter.
func (*Formatter) Format ¶
Format formats either a struct or a slice, returning only the selected fields (or all if none specified).
Example ¶
var w http.ResponseWriter var r *http.Request type APIResult struct { Foo int `json:"foo"` Bar string `json:"bar"` } f := NewFormatter() res := &APIResult{Foo: 1, Bar: "bar"} o, err := f.Format(res, FieldsFromRequest(r)) if err != nil { // handle error } err = json.NewEncoder(w).Encode(o) // {"foo": 1} if err != nil { // handle error }
Output:
Click to show internal directories.
Click to hide internal directories.