server

package
v0.5.0 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Jul 29, 2024 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Constants

View Source
const (
	HeaderKeyLocation    = "Location"
	LinkAttributeSelf    = "self"
	LinkAttributeRelated = "related"
)

Variables

This section is empty.

Functions

func Error

func Error(w http.ResponseWriter, err error, status int, options ...WriteOptions)

Error returns a JSON:API formatted document containing the provided error. If the error is of type jsonapi.Error, it is marshaled as is; otherwise the error text is marshaled into the document payload.

As with ResponseWriter.Write(), the caller should ensure no other calls are made to w after Write() is called.

func Write

func Write(w http.ResponseWriter, data any, status int, options ...WriteOptions)

Write writes the http response to the response writer. If data is a struct, it is marshaled into the JSON:API document format as the primary data. If data is of type jsonapi.Document, the document is written as is. Provide WriteOptions to alter default behavior.

As with ResponseWriter.Write(), the caller should ensure no other calls are made to w after Write() is called.

Types

type Config

type Config struct {
	// contains filtered or unexported fields
}

func DefaultConfig

func DefaultConfig() Config

func (*Config) Apply

func (c *Config) Apply(options ...Options)

func (*Config) ApplyWriteOptions

func (c *Config) ApplyWriteOptions(options ...WriteOptions)

type DocumentOptions

type DocumentOptions = func(http.ResponseWriter, *jsonapi.Document) error

type Handler

type Handler struct {
	Config // Configuration options for the handler.
	// contains filtered or unexported fields
}

Handler wraps an http handler, providing JSON:API context to downstream consumers.

By default, Handler determines context from the request url:

":base/:type"                        // for resource type
":base/:type/:id"                    // for resource type and resource id
":base/:type/:id/relationships/:ref" // for resource type, id, and relationship name
":base/:type/:id/:ref"               // for type, id, relationship, and if the request is for related resources.

This behavior and others can be modified via configuration Options. Handler implements http.Handler and can be used anywhere http handlers are accepted.

Handler zero values are not initialized; use the Handle function to create a new instance.

func Handle

func Handle(handler http.Handler, options ...Options) Handler

Handle returns a Handler, which wraps the provided http handler. The provided resolver supplies the JSON:API request context, which is injected into the http request's context when the handler is invoked. This context can then be retrieved downstream via jsonapi.GetContext().

func (Handler) ServeHTTP

func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles incoming http requests, and injects the JSON:API request context into the http request instance.

type Middleware

type Middleware = func(next http.Handler) http.Handler

type Options

type Options func(*Config)

func WithContextResolver

func WithContextResolver(resolver jsonapi.RequestContextResolver) Options

func WithMiddleware

func WithMiddleware(middleware Middleware) Options

type Relationship

type Relationship struct {
	GetRef    http.Handler // GetRef handles requests to fetch a specific resource relationship.
	UpdateRef http.Handler // UpdateRef handles requests to update a specific resource relationship.
	AddRef    http.Handler // AddRef handles requests to add a specific resource relationship.
	RemoveRef http.Handler // RemoveRef handles requests to remove a specific resource relationship.
}

Relationship handlers route requests that correspond to a resource's relationships. Supported requests include GetRef, UpdateRef, AddRef, and RemoveRef. If the request does not match the JSON:API specifications for the above handlers, a 404 error is returned to the client

Relationship instances can be used alone or as a handler to a Resource instance's Ref field.

func (Relationship) ServeHTTP

func (h Relationship) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles incoming JSON:API requests for resource relationships.

type RelationshipMux

type RelationshipMux map[string]http.Handler

RelationshipMux is a http handler multiplexer for a resource's relationships. Each handler within the mux corresponds to a specific relationship, indexed the relationship name. If the relationship is not defined, a 404 error is returned to the client.

RelationshipMux must be wrapped by or have a parent handler wrapped by Handle to provide JSON:API request context.

func (RelationshipMux) ServeHTTP

func (h RelationshipMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP handles incoming JSON:API requests for resource relationships.

type Resource

type Resource struct {
	Refs   http.Handler // Refs handles requests to resource relationships.
	Create http.Handler // Create handles requests to create new resources.
	List   http.Handler // List handles requests to list resource collections.
	Get    http.Handler // Get handles requests to fetch a specific resource.
	Update http.Handler // Update handles requests to update a specific resource.
	Delete http.Handler // Delete handles requests to delete a specific resource.
}

Resource is a collection of handlers for resource endpoints. Each handler corresponds to a specific JSON:API resource operation, such as Create, List, Get, Update, etc. The request type is determined by the HTTP method and the JSON:API context. Resource instances are intended to be used in conjunction with ResourceMux.

Resource must be wrapped by or have a parent handler wrapped by Handle to provide JSON:API request context.

The handler members are optional. If the corresponding request handler is nil, the request is rejected with a 404 Not Found response.

If the request method does not conform to the JSON:API specification, the request is rejected with a 405 Method Not Allowed response.

func (Resource) ServeHTTP

func (h Resource) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP routes incoming JSON:API requests to the appropriate resource operation.

type ResourceMux

type ResourceMux map[string]http.Handler

ResourceMux is similar to http.ServeMux, but instead of routing requests directly from URL patterns, routes are determined by JSON:API context resource type. Add resource handlers explicitly or via the ResourceMux's Handle() method. When an incoming request is received, and the JSON:API request context is resolved, the handler that resolves the request will be determined by the request context's resource type. Undefined resource requests will return 404 responses.

ResourceMux must have be wrapped by or have a parent handler wrapped by Handle to provide JSON:API request context.

func (ResourceMux) Handle

func (m ResourceMux) Handle(resource string, handler http.Handler)

Handle adds a request handler to the mux. All requests associated with the provided resource type will be served by the provided handler.

func (ResourceMux) ServeHTTP

func (m ResourceMux) ServeHTTP(w http.ResponseWriter, r *http.Request)

ServeHTTP uses the embedded JSON:API request context to forward requests to their associated handler. If no handler is found, a 404 is returned to the client.

type ResponseRecorder

type ResponseRecorder struct {
	Status        int               // The response status code.
	HeaderMap     http.Header       // The response headers.
	Document      *jsonapi.Document // The response document payload.
	JSONUnmarshal jsonUnmarshalFunc // A function that unmarshals JSON documents. Defaults to [json.Unmarshal].
	JSONMarshal   jsonMarshalFunc   // A function that marshals JSON documents. Defaults to [json.Marshal].
}

ResponseRecorder rr implements http.ResponseWriter, capturing WriteHeader() and Write() calls into its instance members. To send recorded data to a response writer w, call rr.Flush(w).

The zero value of ResponseRecorder is uninitialized; use the NewRecorder() function to create a new instance.

func NewRecorder

func NewRecorder() *ResponseRecorder

NewRecorder returns an initialized ResponseRecorder.

func (ResponseRecorder) Flush

func (ww ResponseRecorder) Flush(w http.ResponseWriter)

Flush writes the status code, headers, and document to w.

func (*ResponseRecorder) Header

func (ww *ResponseRecorder) Header() http.Header

Header returns a header map. It is the same header map used in a standard http response writer.

func (*ResponseRecorder) Write

func (ww *ResponseRecorder) Write(p []byte) (int, error)

Write stores the content of p into an internal buffer.

func (*ResponseRecorder) WriteHeader

func (ww *ResponseRecorder) WriteHeader(status int)

WriteHeader stores the status value in memory.

type WriteOptions

type WriteOptions func(*Config)

func WithDocumentOptions

func WithDocumentOptions(options DocumentOptions) WriteOptions

func WithJSONMarshaler

func WithJSONMarshaler(marshal jsonMarshalFunc) WriteOptions
func WriteLink(key string, href string) WriteOptions

WriteLink adds a URL to the response document's links attribute with the provided key.

func WriteLocationHeader

func WriteLocationHeader(baseURL string, resolver jsonapi.URLResolver) WriteOptions

WriteLocationHeader adds the "Location" http header to the response. The resulting URL is based on the primary data resource's type and id.

func WriteMeta

func WriteMeta(key string, value any) WriteOptions

WriteMeta adds a key/value pair to the response document's meta attribute.

func WriteNavigationLinks(r *http.Request, info map[string]query.Page) WriteOptions

WriteNavigationLinks adds pagination URLs to the response document's links attribute.

func WriteRef

func WriteRef(name string) WriteOptions

WriteRef overwrites the primary data with the primary data's relationship, referenced by name.

func WriteResourceLinks(baseURL string, resolver jsonapi.URLResolver) WriteOptions

WriteResourceLinks applies the "self" and "related" links to all resources and resource relationships embedded in the response document.

func WriteSelfLink(r *http.Request) WriteOptions

WriteSelfLink adds the full request URL to the response document's links attribute.

func WriteSortedPrimaryData

func WriteSortedPrimaryData(cmp jsonapi.Comparator, criterion []query.Sort) WriteOptions

WriteSortedPrimaryData orders resources in the response document according to the specified sort criterion.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL