resource

package
v0.12.1 Latest Latest
Warning

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

Go to latest
Published: Oct 17, 2025 License: MIT Imports: 15 Imported by: 0

README

RESTful resource handler

Resource

Resource wraps an object that implements method handlers as actual methods of a class. Resource will provide the http.Handler and web.Handler entry points, and handle errors and OPTIONS and 403 errors directly.

Resource supports a special Check() method to validate and prepare the request before being passed to the dedicated method handler.

If Check isn't implemented, WithChecker() can be used during the New call to set one. Otherwise the DefaultChecker will be used.

Resource will check for Get, Head, Post, Put, Delete, Options and Patch methods, but WithMethod() can be used during the New call for setting custom ones or replacing/deleting a detected one.

If the Peek method doesn't exist, Get will be used. If the Options method doesn't exist, a simple implementation will be provided.

Resource offers a Methods() method with the list of supported HTTP methods. This slice can be safely modified.

Resource deals with the 403 Method Not Allowed directly and with bad req.URL.Paths when using the DefaultChecker.

Signatures

Resource supports two signatures for Check and also two signatures for the method handlers.

The recommended workflow is to use Check to return a resource data pointer using

Check(*http.Request) (*http.Request, T, error)

but one with implicit nil data is also tested for.

Check(*http.Request) (*http.Request, error)

The data pointer can then be received by the FOO method handler via

Foo(http.ResponseWriter, *http.Request, T) error

but one without data pointer is also tested for.

Foo(http.ResponseWriter, *http.Request) error
JSON

Resource extends the standard req.Form handling with its own ParseForm() method that reads the content-type, handles JSON content, and returns an HTTP 400 error in case of problems.

Renderers

Resource allows the registration of supported Media Types using the WithRenderer() option, and then the Render() method will call the correct one after checking the request's preference.

If one wants to return a particular type when none of the supported media types are acceptable, it can be specified using the WithIdentity() option.

For convenience a RenderJSON and RenderHTML helpers are provided.

New() will automatically test for RenderJSON, RenderHTML and RenderTXT methods in the object and registered JSON, HTML and TXT renderers for the Resource accordingly, but the identity representation won't be assumed.

The RenderFunc() helper can be used to turn an any rendering handler into a HandlerFunc[T].

Helpers

  • RenderJSON
  • RenderHTML
  • SetHeader

Documentation

Overview

Package resource implements a RESTful resource handler

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func DefaultChecker

func DefaultChecker[T any](req *http.Request) (*http.Request, T, error)

DefaultChecker is happy with any request that can resolve a valid path but it doesn't do any alteration to the request or its context.

func NewRouteParamsMiddleware added in v0.6.2

func NewRouteParamsMiddleware(h RouteParamsFunc) func(http.Handler) http.Handler

NewRouteParamsMiddleware creates a standard HTTP middleware to attach a RouteParams handler to all requests.

func RenderHTML

func RenderHTML(rw http.ResponseWriter, req *http.Request, code int, tmpl *template.Template, data any) error

RenderHTML compiles an html/template and sends it to the client after setting Content-Type (if not already set) and Content-Length with a given HTTP status code. For HEAD only Content-Type is set.

func RenderJSON

func RenderJSON(rw http.ResponseWriter, req *http.Request, code int, data any) error

RenderJSON encodes the data as JSON and sends it to the client after setting Content-Type (if not already set) and Content-Length with the specified HTTP status code. For HEAD only Content-Type is set.

func RenderTXT added in v0.12.0

func RenderTXT(rw http.ResponseWriter, req *http.Request, code int,
	data any) error

RenderTXT renders plain text with the specified HTTP status code.

func RenderTemplate added in v0.12.0

func RenderTemplate(rw http.ResponseWriter, req *http.Request, code int, tmpl *template.Template, data any) error

RenderTemplate compiles a text/template and sends it to the client with a given HTTP status code. Content-Type must be set by the caller before calling this function. Content-Length is set automatically. For HEAD requests only status code is written.

func RouteParamAll added in v0.6.6

func RouteParamAll[T any](t RouteParamsTable, key string) (values []T, ok bool)

RouteParamAll is an alternative to [RouteParamsTable.Last() that will only succeed if the parameter values are of the requested type.

func RouteParamFirst added in v0.6.6

func RouteParamFirst[T any](t RouteParamsTable, key string) (value T, ok bool)

RouteParamFirst is an alternative to [RouteParamsTable.First() that will only succeed if the parameter is of the requested type.

func RouteParamLast added in v0.6.6

func RouteParamLast[T any](t RouteParamsTable, key string) (value T, ok bool)

RouteParamLast is an alternative to [RouteParamsTable.Last() that will only succeed if the parameter is of the requested type.

func RouteParamValueAllBool added in v0.6.6

func RouteParamValueAllBool[T core.Bool](t RouteParamsTable, key string) (values []T, found bool, err error)

RouteParamValueAllBool attempts to a parse a string values of a parameter into core.Bool values, and indicator if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueAllFloat added in v0.6.6

func RouteParamValueAllFloat[T core.Float](t RouteParamsTable, key string) (values []T, found bool, err error)

RouteParamValueAllFloat attempts to a parse a string values of a parameter into core.Float values, and indicator if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueAllFloatInRange added in v0.6.6

func RouteParamValueAllFloatInRange[T core.Float](t RouteParamsTable, key string,
	minV, maxV T) (values []T, found bool, err error)

RouteParamValueAllFloatInRange attempts to a parse a string values of a parameter into core.Float values and verify they are within the given boundaries. It also returns and indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueAllSigned added in v0.6.6

func RouteParamValueAllSigned[T core.Signed](t RouteParamsTable, key string,
	base int) (values []T, found bool, err error)

RouteParamValueAllSigned attempts to a parse a string values of a parameter into core.Signed values, and indicator if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueAllSignedInRange added in v0.6.6

func RouteParamValueAllSignedInRange[T core.Signed](t RouteParamsTable, key string, base int,
	minV, maxV T) (values []T, found bool, err error)

RouteParamValueAllSignedInRange attempts to a parse a string values of a parameter into core.Signed values and verify they are within the given boundaries. It also returns and indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueAllUnsigned added in v0.6.6

func RouteParamValueAllUnsigned[T core.Unsigned](t RouteParamsTable, key string,
	base int) (values []T, found bool, err error)

RouteParamValueAllUnsigned attempts to a parse a string values of a parameter into core.Unsigned values, and indicator if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueAllUnsignedInRange added in v0.6.6

func RouteParamValueAllUnsignedInRange[T core.Unsigned](t RouteParamsTable, key string, base int,
	minV, maxV T) (values []T, found bool, err error)

RouteParamValueAllUnsignedInRange attempts to a parse a string values of a parameter into core.Unsigned values and verify they are within the given boundaries. It also returns and indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueFirstBool added in v0.6.6

func RouteParamValueFirstBool[T core.Bool](t RouteParamsTable, key string) (value T, found bool, err error)

RouteParamValueFirstBool attempts to a parse a string parameter into a core.Bool value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueFirstFloat added in v0.6.6

func RouteParamValueFirstFloat[T core.Float](t RouteParamsTable, key string) (value T, found bool, err error)

RouteParamValueFirstFloat attempts to a parse a string parameter into a core.Float value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueFirstFloatInRange added in v0.6.6

func RouteParamValueFirstFloatInRange[T core.Float](t RouteParamsTable, key string,
	minV, maxV T) (value T, found bool, err error)

RouteParamValueFirstFloatInRange attempts to a parse a string parameter into a core.Float value, and verify they are within the given boundaries. It also returns an indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueFirstSigned added in v0.6.6

func RouteParamValueFirstSigned[T core.Signed](t RouteParamsTable, key string,
	base int) (value T, found bool, err error)

RouteParamValueFirstSigned attempts to a parse a string parameter into a core.Signed value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueFirstSignedInRange added in v0.6.6

func RouteParamValueFirstSignedInRange[T core.Signed](t RouteParamsTable, key string, base int,
	minV, maxV T) (value T, found bool, err error)

RouteParamValueFirstSignedInRange attempts to a parse a string parameter into a core.Signed value, and verify they are within the given boundaries. It also returns an indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueFirstUnsigned added in v0.6.6

func RouteParamValueFirstUnsigned[T core.Unsigned](t RouteParamsTable, key string,
	base int) (value T, found bool, err error)

RouteParamValueFirstUnsigned attempts to a parse a string parameter into a core.Unsigned value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueFirstUnsignedInRange added in v0.6.6

func RouteParamValueFirstUnsignedInRange[T core.Unsigned](t RouteParamsTable, key string, base int,
	minV, maxV T) (value T, found bool, err error)

RouteParamValueFirstUnsignedInRange attempts to a parse a string parameter into a core.Unsigned value, and verify they are within the given boundaries. It also returns an indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueLastBool added in v0.6.6

func RouteParamValueLastBool[T core.Bool](t RouteParamsTable, key string) (value T, found bool, err error)

RouteParamValueLastBool attempts to a parse a string parameter into a core.Bool value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueLastFloat added in v0.6.6

func RouteParamValueLastFloat[T core.Float](t RouteParamsTable, key string) (value T, found bool, err error)

RouteParamValueLastFloat attempts to a parse a string parameter into a core.Float value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueLastFloatInRange added in v0.6.6

func RouteParamValueLastFloatInRange[T core.Float](t RouteParamsTable, key string,
	minV, maxV T) (value T, found bool, err error)

RouteParamValueLastFloatInRange attempts to a parse a string parameter into a core.Float value, and verify they are within the given boundaries. It also returns an indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueLastSigned added in v0.6.6

func RouteParamValueLastSigned[T core.Signed](t RouteParamsTable, key string,
	base int) (value T, found bool, err error)

RouteParamValueLastSigned attempts to a parse a string parameter into a core.Signed value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueLastSignedInRange added in v0.6.6

func RouteParamValueLastSignedInRange[T core.Signed](t RouteParamsTable, key string, base int,
	minV, maxV T) (value T, found bool, err error)

RouteParamValueLastSignedInRange attempts to a parse a string parameter into a core.Signed value, and verify they are within the given boundaries. It also returns an indicator if the parameter was present, and potentially an error of strconv.NumError type.

func RouteParamValueLastUnsigned added in v0.6.6

func RouteParamValueLastUnsigned[T core.Unsigned](t RouteParamsTable, key string,
	base int) (value T, found bool, err error)

RouteParamValueLastUnsigned attempts to a parse a string parameter into a core.Unsigned value, if the parameter was present, and potentially a parse error of strconv.NumError type.

func RouteParamValueLastUnsignedInRange added in v0.6.6

func RouteParamValueLastUnsignedInRange[T core.Unsigned](t RouteParamsTable, key string, base int,
	minV, maxV T) (value T, found bool, err error)

RouteParamValueLastUnsignedInRange attempts to a parse a string parameter into a core.Unsigned value, and verify they are within the given boundaries. It also returns an indicator if the parameter was present, and potentially an error of strconv.NumError type.

func SetCache added in v0.6.4

func SetCache(rw http.ResponseWriter, d time.Duration)

SetCache sets the Cache-Control header. a Negative value is translated in "private", values of a second or longer translated to "max-age", and otherwise "no-cache"

func SetHeader

func SetHeader(rw http.ResponseWriter, key, value string, args ...any)

SetHeader sets a header value, optionally formatted.

func SetHeaderUnlessExists added in v0.6.4

func SetHeaderUnlessExists(rw http.ResponseWriter, key, value string, args ...any)

SetHeaderUnlessExists sets a header value if it's not already set. Optional value formatting supported.

func SetNoCache added in v0.7.0

func SetNoCache(rw http.ResponseWriter)

SetNoCache sets the Cache-Control header to "no-cache"

func WithRouteParams added in v0.6.2

func WithRouteParams(ctx context.Context, h RouteParamsFunc) context.Context

WithRouteParams attaches a RouteParams handler to the context

Types

type Checker

type Checker interface {
	Check(*http.Request) (*http.Request, error)
}

Checker is a resource that knows to validate its requests

type CheckerFunc

type CheckerFunc[T any] func(*http.Request) (*http.Request, T, error)

CheckerFunc is the signature of a function that pre-validates requests and returns relevant data

type Deleter

type Deleter interface {
	Delete(http.ResponseWriter, *http.Request) error
}

Deleter represents a resource that handles DELETE requests.

type Getter

type Getter interface {
	Get(http.ResponseWriter, *http.Request) error
}

Getter represents a resource that handles GET requests.

type HTMLRenderer added in v0.12.0

type HTMLRenderer[T any] interface {
	RenderHTML(http.ResponseWriter, *http.Request, T) error
}

HTMLRenderer represents the legacy HTML renderer interface

type HTMLRendererWithCode added in v0.12.0

type HTMLRendererWithCode[T any] interface {
	RenderHTML(http.ResponseWriter, *http.Request, int, T) error
}

HTMLRendererWithCode represents the code-aware HTML renderer interface

type HandlerFunc

type HandlerFunc[T any] func(http.ResponseWriter, *http.Request, T) error

HandlerFunc represents a function web.HandlerFunc but taking a data parameter.

func AsHandlerFunc

func AsHandlerFunc[T any](fn web.HandlerFunc) HandlerFunc[T]

AsHandlerFunc wraps a web.HandlerFunc into a HandlerFunc, discarding the data pointer.

func RenderFunc

func RenderFunc[T any](fn func(http.ResponseWriter, *http.Request, any) error) HandlerFunc[T]

RenderFunc converts a generic renderer taking any as data type into a stricter one taking *T instead.

type JSONRenderer added in v0.12.0

type JSONRenderer[T any] interface {
	RenderJSON(http.ResponseWriter, *http.Request, T) error
}

JSONRenderer represents the legacy JSON renderer interface

type JSONRendererWithCode added in v0.12.0

type JSONRendererWithCode[T any] interface {
	RenderJSON(http.ResponseWriter, *http.Request, int, T) error
}

JSONRendererWithCode represents the code-aware JSON renderer interface

type OptionFunc

type OptionFunc[T any] func(*Resource[T]) error

An OptionFunc configures the Resource during a New call. They might fail if used after the initialization.

func WithChecker

func WithChecker[T any](fn CheckerFunc[T]) OptionFunc[T]

WithChecker will force a specific CheckerFunc when initializing the Resource. If the argument is `nil` DefaultChecker will be used as if the `Check` function didn't exist.

func WithHTML

func WithHTML[T any](fn RendererFunc[T]) OptionFunc[T]

WithHTML is a shortcut for WithRendererCode for consts.HTML.

func WithIdentity

func WithIdentity[T any](mediaType string) OptionFunc[T]

WithIdentity specifies the media type to use when nothing is acceptable for the client

func WithJSON

func WithJSON[T any](fn RendererFunc[T]) OptionFunc[T]

WithJSON is a shortcut for WithRendererCode for [JSON]. If no custom handler is provided, the generic RenderJSON will be used.

func WithMethod

func WithMethod[T any](method string, fn HandlerFunc[T]) OptionFunc[T]

WithMethod sets a custom method handler during the New call.

func WithRenderer

func WithRenderer[T any](mediaType string, fn HandlerFunc[T]) OptionFunc[T]

WithRenderer provides a custom renderer for the specified media type

func WithRendererCode added in v0.12.0

func WithRendererCode[T any](mediaType string, fn RendererFunc[T]) OptionFunc[T]

WithRendererCode provides a custom renderer with status code support for the specified media type

func WithTXT added in v0.12.0

func WithTXT[T any](fn RendererFunc[T]) OptionFunc[T]

WithTXT is a shortcut for WithRendererCode for consts.TXT.

func WithTemplate added in v0.12.0

func WithTemplate[T any](mediaType string, fn RendererFunc[T]) OptionFunc[T]

WithTemplate is a helper for registering template renderers with a specific media type. The mediaType parameter specifies the Content-Type that the template will output.

type Optioner

type Optioner interface {
	Options(http.ResponseWriter, *http.Request) error
}

Optioner represents a resource that handles OPTIONS requests.

type Patcher

type Patcher interface {
	Patch(http.ResponseWriter, *http.Request) error
}

Patcher represents a resource that handles PATCH requests.

type Peeker

type Peeker interface {
	Head(http.ResponseWriter, *http.Request) error
}

Peeker represents a resource that handles HEAD requests.

type Poster

type Poster interface {
	Post(http.ResponseWriter, *http.Request) error
}

Poster represents a resource that handles POST requests.

type Putter

type Putter interface {
	Put(http.ResponseWriter, *http.Request) error
}

Putter represents a resource that handles PUT requests.

type RendererFunc added in v0.12.0

type RendererFunc[T any] func(http.ResponseWriter, *http.Request, int, T) error

RendererFunc represents a renderer function that can handle custom HTTP status codes.

type Resource

type Resource[T any] struct {
	// contains filtered or unexported fields
}

Resource is an http.Handler built around a given object and a data type.

func Must

func Must[T any](x any, options ...OptionFunc[T]) *Resource[T]

Must creates a Resource just like New, but panics if there is an error.

func New

func New[T any](x any, options ...OptionFunc[T]) (*Resource[T], error)

New creates a Resource using the provided handler object and the specified data type.

func (*Resource[T]) Methods

func (r *Resource[T]) Methods() []string

Methods returns a list of all supported HTTP Methods

func (*Resource[T]) ParseForm

func (*Resource[T]) ParseForm(req *http.Request, maxMemory int64) error

ParseForm is similar to the standard request.ParseForm() but it handles urlencoded, multipart and JSON. For nested JSON objects ParseForm uses dots to join keys.

func (*Resource[T]) PreferredMediaType

func (r *Resource[T]) PreferredMediaType(req *http.Request) (string, error)

PreferredMediaType identifies the best Media Type to serve to a particular request. If nothing is acceptable, but an "identity" type has been set, that will be returned instead of a 406 error.

func (*Resource[T]) Render

func (r *Resource[T]) Render(rw http.ResponseWriter, req *http.Request, data T) error

Render uses the Accept header to choose what renderer to use. If nothing acceptable is supported, but an "identity" type has been set, that will be used.

func (*Resource[T]) RenderWithCode added in v0.12.0

func (r *Resource[T]) RenderWithCode(rw http.ResponseWriter, req *http.Request, code int, data T) error

RenderWithCode uses the Accept header to choose what renderer to use and writes the specified HTTP status code. Only works with code-aware renderers.

func (*Resource[T]) ServeHTTP

func (r *Resource[T]) ServeHTTP(rw http.ResponseWriter, req *http.Request)

ServeHTTP handles the request initially using the TryServeHTTP method, and then calling web.HandleError if there is any problem.

func (*Resource[T]) TryServeHTTP

func (r *Resource[T]) TryServeHTTP(rw http.ResponseWriter, req *http.Request) error

TryServeHTTP attempts to handle the request, and returns an error in the case of problems instead of handling it locally. This method converts panics into errors in case they occur.

type RouteParamsFunc added in v0.6.2

type RouteParamsFunc func(context.Context) (path string, params RouteParamsTable, err error)

RouteParamsFunc represents a helper that extracts the request parameters as provided by the

func RouteParams added in v0.6.2

func RouteParams(ctx context.Context) (RouteParamsFunc, bool)

RouteParams extracts a RouteParams handlers from the context

type RouteParamsTable added in v0.6.2

type RouteParamsTable map[string][]any

RouteParamsTable is a list a URL params

func Resolve added in v0.6.2

func Resolve(req *http.Request) (path string, params RouteParamsTable, err error)

Resolve expands on web.Resolve using RouteParams() to get the URL params from the HTTP Router additionally to the Route Path. It will fallback to web.Resolve if a RouteParams handlers isn't present, and also validates the path.

func (RouteParamsTable) Add added in v0.6.2

func (params RouteParamsTable) Add(key string, value any)

Add appends a value for the given parameter

func (RouteParamsTable) All added in v0.6.2

func (params RouteParamsTable) All(key string) ([]any, bool)

All returns all stored values for a parameter

func (RouteParamsTable) First added in v0.6.2

func (params RouteParamsTable) First(key string) (any, bool)

First returns the first stored value for a parameter

func (RouteParamsTable) Last added in v0.6.2

func (params RouteParamsTable) Last(key string) (any, bool)

Last returns the last stored value for a parameter

func (RouteParamsTable) Len added in v0.6.2

func (params RouteParamsTable) Len(key string) (int, bool)

Len tells how many parameters are stored in the table

func (RouteParamsTable) Params added in v0.6.2

func (params RouteParamsTable) Params() []string

Params lists the names of all stored parameters

type TChecker

type TChecker[T any] interface {
	Check(*http.Request) (*http.Request, T, error)
}

TChecker is a resource that knows how validate its requests, and returns the relevant data

type TDeleter

type TDeleter[T any] interface {
	Delete(http.ResponseWriter, *http.Request, T) error
}

TDeleter represents a resource that handles DELETE requests with a data field.

type TGetter

type TGetter[T any] interface {
	Get(http.ResponseWriter, *http.Request, T) error
}

TGetter represents a resource that handles GET requests with a data field.

type TOptioner

type TOptioner[T any] interface {
	Options(http.ResponseWriter, *http.Request, T) error
}

TOptioner represents a resource that handles OPTIONS requests with a data field.

type TPatcher

type TPatcher[T any] interface {
	Patch(http.ResponseWriter, *http.Request, T) error
}

TPatcher represents a resource that handles PATCH requests with a data field.

type TPeeker

type TPeeker[T any] interface {
	Head(http.ResponseWriter, *http.Request, T) error
}

TPeeker represents a resource that handles HEAD requests with a data field.

type TPoster

type TPoster[T any] interface {
	Post(http.ResponseWriter, *http.Request, T) error
}

TPoster represents a resource that handles POST requests with a data field.

type TPutter

type TPutter[T any] interface {
	Put(http.ResponseWriter, *http.Request, T) error
}

TPutter represents a resource that handles PUT requests with a data field.

type TXTRenderer added in v0.12.0

type TXTRenderer[T any] interface {
	RenderTXT(http.ResponseWriter, *http.Request, T) error
}

TXTRenderer represents the legacy TXT renderer interface

type TXTRendererWithCode added in v0.12.0

type TXTRendererWithCode[T any] interface {
	RenderTXT(http.ResponseWriter, *http.Request, int, T) error
}

TXTRendererWithCode represents the code-aware TXT renderer interface

type TemplateRenderer added in v0.12.0

type TemplateRenderer[T any] interface {
	RenderTemplate(http.ResponseWriter, *http.Request, T) error
}

TemplateRenderer represents the legacy template renderer interface

type TemplateRendererWithCode added in v0.12.0

type TemplateRendererWithCode[T any] interface {
	RenderTemplate(http.ResponseWriter, *http.Request, int, T) error
}

TemplateRendererWithCode represents the code-aware template renderer interface

Jump to

Keyboard shortcuts

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