Documentation
¶
Overview ¶
Package server provides HTTP server utilities for building JSON:API compliant web services. It includes request context management, resource handlers, and routing utilities that simplify the creation of JSON:API endpoints following the specification.
Index ¶
- func DefaultHandler(mux ResourceHandlerMux) http.Handler
- func Error(w http.ResponseWriter, err error, status int)
- func SetRequestContext(parent context.Context, value *RequestContext) context.Context
- func UseContentNegotiation(next http.Handler) http.Handler
- func UseRequestContextResolver(next http.Handler, resolver RequestContextResolver) http.Handler
- func Write(w http.ResponseWriter, body *jsonapi.Document, status int)
- type DefaultContextResolver
- type HandlerFunc
- type RelationshipHandler
- type RequestContext
- func (r RequestContext) GetFields(req *http.Request, resourceType string) []string
- func (r RequestContext) GetFilterParam(req *http.Request, key string) string
- func (r RequestContext) GetPageParam(req *http.Request, key string) string
- func (r RequestContext) GetSort(req *http.Request) []string
- func (r RequestContext) ShouldInclude(req *http.Request, path string) bool
- type RequestContextResolver
- type ResourceHandler
- type ResourceHandlerMux
- type Response
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func DefaultHandler ¶
func DefaultHandler(mux ResourceHandlerMux) http.Handler
DefaultHandler creates a default HTTP handler with standard JSON:API routes configured. It sets up all the conventional JSON:API endpoints including resource CRUD operations and relationship management endpoints, using the provided ResourceHandlerMux for routing.
The following endpoints are configured:
"GET /{type}" // Search/list resources of a type "GET /{type}/{id}" // Get a single resource by ID "POST /{type}" // Create a new resource "PATCH /{type}/{id}" // Update an existing resource "DELETE /{type}/{id}" // Delete a resource "GET /{type}/{id}/relationships/{relationship}" // Get a resource's relationship "GET /{type}/{id}/{related}" // Get related resources "POST /{type}/{id}/relationships/{relationship}" // Add to a to-many relationship "PATCH /{type}/{id}/relationships/{relationship}" // Update a relationship "DELETE /{type}/{id}/relationships/{relationship}" // Remove from a to-many relationship
func Error ¶
func Error(w http.ResponseWriter, err error, status int)
Error writes a JSON:API error response to the provided http.ResponseWriter. It accepts multiple types of error inputs and formats them according to the JSON:API specification for error objects.
Supported error types:
- jsonapi.Error: Used directly
- jsonapi.MultiError: All errors are included in the response
- Other error types: Converted to jsonapi.Error with the provided status
The response will have Content-Type set to application/vnd.api+json and include a JSON:API document containing the formatted error(s).
func SetRequestContext ¶
func SetRequestContext(parent context.Context, value *RequestContext) context.Context
SetRequestContext stores a RequestContext in the provided context and returns the new context. This is typically used in middleware to make request context information available to downstream handlers.
func UseContentNegotiation ¶
UseContentNegotiation provides JSON:API content negotiation middleware. It validates Content-Type and Accept headers according to JSON:API specification. Returns 415 Unsupported Media Type for invalid Content-Type on requests with body. Returns 406 Not Acceptable for invalid Accept headers.
func UseRequestContextResolver ¶
func UseRequestContextResolver(next http.Handler, resolver RequestContextResolver) http.Handler
UseRequestContextResolver creates middleware that resolves request context information using the provided resolver and makes it available to downstream handlers. If context resolution fails, it returns an HTTP 500 error.
func Write ¶
func Write(w http.ResponseWriter, body *jsonapi.Document, status int)
Write sends a JSON:API document response to the client with the specified HTTP status code. The response will have Content-Type set to application/vnd.api+json and include the JSON-encoded document body. If the body is nil, only the status code will be written without a response body. The function handles setting the appropriate Content-Type header and encoding the document as JSON.
Types ¶
type DefaultContextResolver ¶
type DefaultContextResolver struct{}
DefaultContextResolver is the default implementation of RequestContextResolver. It extracts JSON:API context information from URL path parameters using Go's standard HTTP router path value extraction. This resolver works with the standard JSON:API URL patterns.
func (DefaultContextResolver) ResolveRequestContext ¶
func (DefaultContextResolver) ResolveRequestContext(r *http.Request) (*RequestContext, error)
ResolveRequestContext implements the RequestContextResolver interface. It extracts resource type, ID, and relationship information from the HTTP request URL path parameters and constructs a RequestContext with the parsed information.
type HandlerFunc ¶
type HandlerFunc func(*RequestContext, *http.Request) (res Response)
HandlerFunc is a function type that processes JSON:API requests and returns structured responses. It receives the parsed request context and HTTP request, and returns a Response struct. This provides a more convenient way to write JSON:API handlers compared to the standard http.HandlerFunc type.
func (HandlerFunc) ServeHTTP ¶
func (h HandlerFunc) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for Handler functions. It calls the handler function with the request context and handles the response formatting, including setting appropriate headers and encoding the JSON:API document body.
type RelationshipHandler ¶
type RelationshipHandler struct { Get http.Handler // Handler for GET requests to fetch relationship linkage Add http.Handler // Handler for POST requests to add to to-many relationships Update http.Handler // Handler for PATCH requests to update relationship linkage Delete http.Handler // Handler for DELETE requests to remove from to-many relationships }
RelationshipHandler provides HTTP handlers for JSON:API relationship operations. It supports the full range of relationship manipulation operations as defined in the JSON:API specification, including fetching, adding, updating, and removing relationship linkages.
func (RelationshipHandler) ServeHTTP ¶
func (rh RelationshipHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for RelationshipHandler. It routes relationship requests to the appropriate handler based on the HTTP method, following JSON:API relationship operation conventions.
type RequestContext ¶
type RequestContext struct { ResourceID string // The ID of the requested resource ResourceType string // The type of the requested resource Relationship string // The name of the requested relationship FetchRelatedResources bool // Whether to fetch related resources instead of relationship linkage }
RequestContext contains parsed information from an HTTP request that is relevant to JSON:API resource operations. It provides structured access to resource identifiers, types, and relationship information extracted from the request URL.
func GetRequestContext ¶
func GetRequestContext(ctx context.Context) (*RequestContext, bool)
GetRequestContext retrieves a RequestContext from the provided context. It returns the RequestContext and a boolean indicating whether the context was found. If no context is found, it returns nil and false.
func (RequestContext) GetFields ¶
func (r RequestContext) GetFields(req *http.Request, resourceType string) []string
GetFields returns the sparse fieldset for a resource type from the request query parameters. It parses the fields[type]=field1,field2 query parameter format. Returns an empty slice if no fields are specified for the resource type.
func (RequestContext) GetFilterParam ¶
func (r RequestContext) GetFilterParam(req *http.Request, key string) string
GetFilterParam returns a filter parameter value from the request query parameters. It parses the filter[key]=value query parameter format. Returns an empty string if the parameter is not found.
func (RequestContext) GetPageParam ¶
func (r RequestContext) GetPageParam(req *http.Request, key string) string
GetPageParam returns a pagination parameter value from the request query parameters. It parses the page[key]=value query parameter format. Returns an empty string if the parameter is not found.
func (RequestContext) GetSort ¶
func (r RequestContext) GetSort(req *http.Request) []string
GetSort returns the sort fields from the request query parameters. It parses the sort=field1,-field2 query parameter format. Returns an empty slice if no sort parameter is specified.
func (RequestContext) ShouldInclude ¶
func (r RequestContext) ShouldInclude(req *http.Request, path string) bool
ShouldInclude checks if a relationship path should be included based on the include query parameter. It parses the include=relationship1,relationship2 format and returns true if the specified path is found in the include list.
type RequestContextResolver ¶
type RequestContextResolver interface { // ResolveRequestContext extracts JSON:API context information from the HTTP request. // It returns a populated RequestContext or an error if the request cannot be parsed. ResolveRequestContext(r *http.Request) (*RequestContext, error) }
RequestContextResolver defines the interface for extracting RequestContext information from HTTP requests. Implementations should parse the request URL and headers to populate the context with relevant JSON:API resource information.
type ResourceHandler ¶
type ResourceHandler struct { Get http.Handler // Handler for GET requests to retrieve a single resource Create http.Handler // Handler for POST requests to create new resources Update http.Handler // Handler for PATCH requests to update existing resources Delete http.Handler // Handler for DELETE requests to remove resources Search http.Handler // Handler for GET requests to search/list resources Relationship http.Handler // Handler for relationship-specific operations }
ResourceHandler provides HTTP handlers for different JSON:API resource operations. It routes requests to appropriate handlers based on the HTTP method and request context, following JSON:API conventions for resource manipulation.
func (ResourceHandler) ServeHTTP ¶
func (rh ResourceHandler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for ResourceHandler. It routes incoming requests to the appropriate handler based on the HTTP method and request context information, following JSON:API routing conventions.
type ResourceHandlerMux ¶
ResourceHandlerMux is a multiplexer that routes requests to different resource handlers based on the resource type. It maps resource type names to their corresponding HTTP handlers, enabling multi-resource JSON:API services.
func (ResourceHandlerMux) ServeHTTP ¶
func (rm ResourceHandlerMux) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP implements the http.Handler interface for ResourceHandlerMux. It routes incoming requests to the appropriate resource handler based on the resource type specified in the request context.
type Response ¶
type Response struct { Status int // HTTP status code for the response Header http.Header // HTTP headers to include in the response Body *jsonapi.Document // JSON:API document to send as the response body }
Response represents a JSON:API HTTP response with status code, headers, and a JSON:API document body. In conjunction with HandlerFunc, Response provides a structured way to return JSON:API compliant responses from handler functions.