Documentation ¶
Index ¶
- Constants
- Variables
- func JoinParamKey(ks []string) string
- func NewRequestContext(ctx context.Context, req *Request) context.Context
- func NewResponseContext(ctx context.Context, res *Response) context.Context
- func SplitComma(s string) []string
- func SplitParamKey(k string) []string
- func ValidAccept(req *http.Request) error
- func ValidClientIDs(req *http.Request, jreq *Request, require Requirement) error
- func ValidDataTypes(req *http.Request, jreq *Request, b DataTypeBits) error
- func ValidIncludes(jreq *Request, is Includes) error
- func ValidParams(req *http.Request) error
- func ValidSorts(jreq *Request, ss Sorts) error
- func ValidType(jreq *Request, t string) error
- type Attributes
- func (a Attributes) Bool(k string) bool
- func (a Attributes) Float(k string) float64
- func (a Attributes) Int(k string) int
- func (a Attributes) NullBool(k string) null.Bool
- func (a Attributes) NullFloat(k string) null.Float
- func (a Attributes) NullInt(k string) null.Int
- func (a Attributes) NullString(k string) null.String
- func (a Attributes) NullTime(k string) null.Time
- func (a Attributes) String(k string) string
- func (a Attributes) Time(k string) time.Time
- type Data
- type DataTypeBits
- type Error
- type ErrorHandler
- type Errors
- type Fieldsets
- type Includes
- type JSONAPI
- type Link
- type Links
- type Meta
- type Middleware
- type Page
- type Relationship
- type Relationships
- type Request
- type Requirement
- type Resource
- type Resourcer
- type Resourcers
- type Resources
- type Response
- func (r *Response) AddError(err error)
- func (r *Response) AddInclude(rr Resourcer)
- func (r *Response) AddIncludes(rrs Resourcers)
- func (r *Response) AddResource(rr Resourcer)
- func (r *Response) AddResources(rrs Resourcers)
- func (r *Response) Header() http.Header
- func (r *Response) SetLocation(url string)
- func (r *Response) SetResource(rr Resourcer)
- func (r *Response) Write()
- type Sort
- type Sorts
Constants ¶
const ( ParamFields = "fields" ParamFilter = "filter" ParamInclude = "include" ParamPage = "page" ParamPageNumber = "page[number]" ParamPageSize = "page[size]" ParamPageOffset = "page[offset]" ParamPageLimit = "page[limit]" ParamPageCursor = "page[cursor]" ParamSort = "sort" )
Standard parameter key constants.
const ( ErrRelationshipMissing = "Missing required relationship %q." ErrRelationshipSingle = "Relationship %q must be a single resource linkage." ErrRelationshipType = "Relationship %q must have type %q." )
Resource error format strings.
const ( HeaderContentType = "Content-Type" HeaderLocation = "Location" )
Commonly used header names.
const ( Asc = "ASC" Desc = "DESC" )
SQL expression constants for ascending and descending order.
const ( ErrAccept = "Request must have %q type in Accept header." ErrParam = "Request has invalid parameter %q." ErrInclude = "Request has unsupported include %q." ErrSort = "Request has unsupported sort field %q." ErrType = "Resources must have type %q." )
Validation error format strings.
const ContentType = "application/vnd.api+json"
ContentType is the Content-Type header value used for JSON API requests and responses.
const ErrInvalidJSON = "Invalid JSON body: %s"
ErrInvalidJSON is the error format string used when a request's JSON body is invalid.
const Version = "1.0"
Version is the version of JSON API that this package implements.
const Wildcard = "*"
Wildcard matches any include path.
Variables ¶
var ( ErrClientID = Error{ Status: http.StatusForbidden, Detail: "Resources cannot have client-generated IDs.", } ErrMissingClientID = Error{ Status: http.StatusForbidden, Detail: "Resources must have client-generated IDs.", } ErrDataNull = Error{ Status: http.StatusBadRequest, Detail: "Request data cannot be null.", } ErrDataSingle = Error{ Status: http.StatusBadRequest, Detail: "Request data cannot be a single resource.", } ErrDataArray = Error{ Status: http.StatusBadRequest, Detail: "Request data cannot be an array of resources.", } )
Validation errors.
var Any = Includes{Wildcard}
Any represents all include paths.
var RegexpFields = regexp.MustCompile(`^fields\[(.*)\]$`)
RegexpFields matches fields parameter keys. First submatch is the resource type.
var RegexpStandardParam = regexp.MustCompile(`^[a-z]+$`)
RegexpStandardParam matches strings following the naming convention for standard parameters.
var StandardParams = map[string]bool{ ParamFields: true, ParamFilter: true, ParamInclude: true, ParamPage: true, ParamSort: true, }
StandardParams is a map containing all standard query parameters defined by JSON API.
Functions ¶
func JoinParamKey ¶
JoinParamKey joins a parameter key slice into a string.
func NewRequestContext ¶
NewRequestContext returns a context that carries a request.
func NewResponseContext ¶
NewResponseContext returns a context that carries a response.
func SplitComma ¶
SplitComma splits a comma-separated list as a string into a slice.
func SplitParamKey ¶
SplitParamKey splits a parameter key into a slice. The parameter key may use square bracket syntax to indicate nested values. For example, "key[one][two]" returns the slice [key one two].
func ValidAccept ¶
ValidAccept returns an error if the request's Accept header does not contain the JSON API content type.
func ValidClientIDs ¶
func ValidClientIDs(req *http.Request, jreq *Request, require Requirement) error
ValidClientIDs returns an error if the request contains any client-generated IDs that do not meet the given requirement. If the request is not a POST request, then no error will be returned.
func ValidDataTypes ¶
func ValidDataTypes(req *http.Request, jreq *Request, b DataTypeBits) error
ValidDataTypes returns an error if the request data is a type (null, single resource, or array) that is not included in b. If b is zero, then the default depends on the request method. POST and PATCH requests only allow a single resource and all other methods only allow null.
func ValidIncludes ¶
ValidIncludes returns an error if the request contains any include paths not found in is.
func ValidParams ¶
ValidParams returns an error if the request contains any invalid query parameters.
func ValidSorts ¶
ValidSorts returns an error if the request contains any sort field not found in ss.
Types ¶
type Attributes ¶
type Attributes map[string]interface{}
Attributes represents an attributes object and stores arbitrary data.
func (Attributes) Bool ¶
func (a Attributes) Bool(k string) bool
Bool returns the value of a bool attribute. It will return false for non-bool or missing attributes.
func (Attributes) Float ¶
func (a Attributes) Float(k string) float64
Float returns the value of a float64 attribute. It will return 0 for non-float64 or missing attributes.
func (Attributes) Int ¶
func (a Attributes) Int(k string) int
Int returns the value of an int attribute. It will return null for non-int or missing attributes.
func (Attributes) NullBool ¶
func (a Attributes) NullBool(k string) null.Bool
NullBool returns the value of a nullable bool attribute. It will return null for non-bool or missing attributes.
func (Attributes) NullFloat ¶
func (a Attributes) NullFloat(k string) null.Float
NullFloat returns the value of a nullable float64 attribute. It will return null for non-float64 or missing attributes.
func (Attributes) NullInt ¶
func (a Attributes) NullInt(k string) null.Int
NullInt returns the value of a nullable int attribute. It will return null for non-int or missing attributes.
func (Attributes) NullString ¶
func (a Attributes) NullString(k string) null.String
NullString returns the value of a nullable string attribute. It will return null for non-string or missing attributes.
func (Attributes) NullTime ¶
func (a Attributes) NullTime(k string) null.Time
NullTime returns the value of a nullable time attribute. It will return null for non-time or missing attributes.
func (Attributes) String ¶
func (a Attributes) String(k string) string
String returns the value of a string attribute or "" for non-string or missing attributes.
type Data ¶
Data represents a resource or a collection of resources.
func (Data) MarshalJSON ¶
MarshalJSON marshals the struct to either a single resource or array of resources.
func (*Data) UnmarshalJSON ¶
UnmarshalJSON unmarshals JSON into the struct. The JSON can be a single resource or an array of resource.
type DataTypeBits ¶
type DataTypeBits int
DataTypeBits specifies the allowed types for the data field of a request.
const ( DataNull DataTypeBits = 1 << iota DataSingle DataArray )
Possible bit flags for request body data types.
type Error ¶
type Error struct { ID string `json:"id,omitempty"` Status int `json:"status,string,omitempty"` Code string `json:"code,omitempty"` Title string `json:"title,omitempty"` Detail string `json:"detail,omitempty"` Source Meta `json:"source,omitempty"` Links Links `json:"links,omitempty"` Meta Meta `json:"meta,omitempty"` }
Error is a JSON API error object.
type ErrorHandler ¶
ErrorHandler is a context handler that calls a function that can return an error that gets added to the JSON API response.
func (ErrorHandler) ServeHTTP ¶
func (eh ErrorHandler) ServeHTTP(ctx context.Context, rw http.ResponseWriter, req *http.Request)
ServeHTTP calls the function and adds any error returned to the JSON API response.
type Fieldsets ¶
Fieldsets defines a map of sparse fieldsets which specifies a slice of allowed fields for resource types. Key is resource type, value is a slice of field names.
type Link ¶
type Link linkFields
Link represents a hyperlink.
func (Link) MarshalJSON ¶
MarshalJSON marshals the link to either a string (if it has no meta data) or an object.
type Middleware ¶
type Middleware struct { // Includes is a list of relationship paths supported by the include // parameter. Use Any to accept all paths. Includes Includes // Sorts defines the supported sort fields. The expression fields defined // here will be copied into the request's sort fields so the expressions // will be available to the handler. Sorts Sorts // The maximum allowed page size and limit. If 0, then no limit is enforced. MaxPageSize, MaxPageLimit int // ClientIDs configures the validation check for client-generated IDs in the // request body. Possible values are Forbidden (the default), Optional, or // Required. Only applies to POST requests. ClientIDs Requirement // Type is the resource type that all resources in the request must have. If // this is an empty string, then all types are allowed. Type string // DataTypes is a bit field that represents the types that are allowed for // the request body data. Possible values are DataNull, DataSingle, and/or // DataArray. Use OR (`|`) to allow multiple types. The defaults are // DataSingle for POST and PATCH requests and DataNull for other methods. DataTypes DataTypeBits // Handler is the context handler that is called if the request is valid. Handler web.ContextHandler }
Middleware is a middleware context handler that performs some JSON API validation on the current request, adds JSON API request and response objects to the current context for the next handler, and writes the response.
func (Middleware) ServeHTTP ¶
func (mw Middleware) ServeHTTP(ctx context.Context, rw http.ResponseWriter, req *http.Request)
ServeHTTP performs validation, initializes the request and response objects, and calls the next handler.
type Relationship ¶
type Relationship struct { Links Links `json:"links,omitempty"` Data *Data `json:"data,omitempty"` Meta Meta `json:"meta,omitempty"` }
Relationship represents a relationship object and stores a reference to a resource object.
type Relationships ¶
type Relationships map[string]*Relationship
Relationships is a map of relationship objects.
type Request ¶
type Request struct { Data *Data `json:"data"` // Params contains the request query parameters. Params url.Values `json:"-"` // Includes is a list of requested relationship paths. nil means the client // did not specify a list. Includes Includes `json:"-"` // Fieldsets is the sparse fieldsets specified in the request. Fieldsets Fieldsets `json:"-"` // Sorts contains the sort fields specified in the request. Sorts Sorts `json:"-"` // Page contains pagination parameter values. Page Page `json:"-"` }
Request contains JSON API request data extracted from an http.Request.
func NewRequest ¶
NewRequest returns a new request populated from an http.Request.
func RequestFromContext ¶
RequestFromContext returns the request stored in ctx.
func (Request) Filter ¶
Filter returns the value of a filter parameter. If a filter doesn't exist, an empty string is returned. Keys can be given to access nested filters.
func (Request) Include ¶
Include returns true if the given relationship path p should be included in the response. This is true if the request did not specify any includes or p was included in the list of includes.
func (Request) Param ¶
Param returns a parameter as a string. If the parameter doesn't exist, an empty string is returned. Multiple keys can be given to access nested parameter values.
func (Request) ParamInt ¶
ParamInt is like Param, except it returns an int or 0 if missing or invalid.
func (Request) ParamNonNegInt ¶
ParamNonNegInt is like ParamInt, except negative integers are invalid.
type Requirement ¶
type Requirement int
Requirement represents the possible requirements for client-generated IDs.
const ( Forbidden Requirement = iota Optional Required )
Possible values for Requirement.
type Resource ¶
type Resource struct { ID string `json:"id"` Type string `json:"type"` Attributes Attributes `json:"attributes,omitempty"` Relationships Relationships `json:"relationships,omitempty"` Links Links `json:"links,omitempty"` Meta Meta `json:"meta,omitempty"` }
Resource represents a resource object.
func (*Resource) AddSingleLinkage ¶
AddSingleLinkage adds a resource linkage object to r's relationships for a single resource. The relationship will have key k and the linked resource has ID id and type t.
func (Resource) LinkageID ¶
LinkageID returns the ID of the resource linkage with relationship key k and an expected type of t.
func (Resource) NullLinkageID ¶
NullLinkageID returns the ID of an optional resource linkage with relationship key k and an expected type of t.
type Resourcer ¶
type Resourcer interface {
Resource() *Resource
}
Resourcer is an interface that wraps a Resource method for returning a resource.
type Resourcers ¶
type Resourcers interface {
Resources() Resources
}
Resourcers is an interface that wraps a Resources method for returning a slice of resources.
type Resources ¶
type Resources []*Resource
Resources is a slice of resources.
type Response ¶
type Response struct { Status int `json:"-"` JSONAPI *JSONAPI `json:"jsonapi,omitempty"` Links Links `json:"links,omitempty"` Data *Data `json:"data,omitempty"` Included Resources `json:"included,omitempty"` Errors []Error `json:"errors,omitempty"` Meta Meta `json:"meta,omitempty"` // Fieldsets defines sparse fieldsets to be applied to all resources in the // response when the response is written. Fieldsets Fieldsets `json:"-"` // contains filtered or unexported fields }
Response represents a JSON API response document.
func NewResponse ¶
func NewResponse(rw http.ResponseWriter) *Response
NewResponse initializes a new response to be written to rw.
func ResponseFromContext ¶
ResponseFromContext returns the response stored in ctx.
func (*Response) AddInclude ¶
AddInclude adds a single resource to the slice of included resources. If the resource is already in the slice, nothing happens.
func (*Response) AddIncludes ¶
func (r *Response) AddIncludes(rrs Resourcers)
AddIncludes adds all resources in rrs to the slice of included resources. If a resource is already in the slice, it won't be added as a duplicate.
func (*Response) AddResource ¶
AddResource adds a single resource to the response data.
func (*Response) AddResources ¶
func (r *Response) AddResources(rrs Resourcers)
AddResources adds all resources in rrs to the response data.
func (*Response) SetLocation ¶
SetLocation sets the Location header to some URL of a created resource.
func (*Response) SetResource ¶
SetResource sets the response data to a single resource.
type Sort ¶
type Sort struct { // Name is the name of the sort field that is used in the sort parameter. Name string // Expr is the actual expression (or column name) that is prefixed with ASC // or DESC depending on the order for this sort field. Expr string // ExprAsc and ExprDesc are the actual expressions for ascending and // descending order for this sort field. ExprAsc, ExprDesc string // Desc is true if this field should be sorted in descending order. Desc bool }
Sort defines a sort field.