resource

package
v0.6.1 Latest Latest
Warning

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

Go to latest
Published: Jul 14, 2024 License: MIT Imports: 11 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 a prepare the request before being passed the 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 403 Method No 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 it's 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

View Source
const (
	// GET represents the HTTP GET Method.
	GET = "GET"
	// HEAD represents the HTTP HEAD Method.
	HEAD = "HEAD"
	// POST represents the HTTP POST Method.
	POST = "POST"
	// PUT represents the HTTP PUT Method.
	PUT = "PUT"
	// DELETE represents the HTTP DELETE Method.
	DELETE = "DELETE"
	// OPTIONS represents the HTTP OPTIONS Method.
	OPTIONS = "OPTIONS"
	// PATCH represents the HTTP PATCH Method.
	PATCH = "PATCH"
)
View Source
const (
	// ContentType is the canonical HTTP Content-Type header.
	ContentType = "Content-Type"
	// ContentLength is the canonical HTTP Content-Length header.
	ContentLength = "Content-Length"

	// JSON is the standard Media Type for JSON content.
	JSON = "application/json; charset=utf-8"
	// HTML is the standard Media Type for HTML content.
	HTML = "text/html; charset=utf-8"
	// TXT is the standard Media Type for plain text content.
	TXT = "text/plain; charset=utf-8"
)

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 RenderHTML

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

RenderHTML compiles an html/template and sends it to the client after setting Content-Type and Content-Length. For HEAD only Content-Type is set.

func RenderHTMLWithCode added in v0.5.4

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

RenderHTMLWithCode compiles an html/template and sends it to the client after setting Content-Type 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, data any) error

RenderJSON encodes the data as JSON and sends it to the client after setting Content-Type and Content-Length. For HEAD only Content-Type is set.

func SetHeader

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

SetHeader sets a header value, optionally formatted.

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 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 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 HandlerFunc[T]) OptionFunc[T]

WithHTML is a shortcut for WithRenderer for 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 HandlerFunc[T]) OptionFunc[T]

WithJSON is a shortcut for WithRenderer 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

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 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]) 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 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.

Jump to

Keyboard shortcuts

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