restfulwrapper

package module
v0.1.4 Latest Latest
Warning

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

Go to latest
Published: Mar 12, 2026 License: MIT Imports: 12 Imported by: 0

README

restfulwrapper

GitHub tag (latest SemVer) PkgGoDev

This is a wrapper around go-restful to make it easier to use.

Usage

This is a simple case of a single API container with a single endpoint.

type API struct{}

type GetMetadata struct {
	restfulwrapper.HTTPMethodGET
	_ string `api:"httppath:/"`
	_ string `api:"doc" description:"Handle a GET request."`
	_ string `api:"notes" description:""`
}
type GetOutput struct{}

func (a *API) Get(ctx context.Context, meta GetMetadata) (output GetOutput, err error) {
	output = GetOutput{}

	// ...

	return output, nil
}

// ...

webService := restfulwrapper.WebService("/api").
	Consumes(restful.MIME_JSON).
	Produces(restful.MIME_JSON)
{
	session := webService.Session()
	session.Register(ctx, "/v1/path/to/service", &API{})
}

container := restful.NewContainer()
container.Add(webService.WebService())

// Use container as you would any `http.Handler`.

An API struct can embed other API structs using httppath:

type API struct{
	_ OtherAPI `api:"httppath:/other-api"`
}

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func NewAPIBodyError

func NewAPIBodyError(bodyError error) error

NewAPIBodyError returns a new error relating to parsing the POST body.

Call this with whatever error you got when parsing the body.

func NewAPIHeaderParameterError

func NewAPIHeaderParameterError(parameter string, parameterError error) error

NewAPIHeaderParameterError returns a new header parameter error.

Call this any time there is any issue at all with a header parameter. For example, if it is required but missing; if it has an incorrect value; or if it needed to be parsed and could not be parsed.

func NewAPIPathParameterError

func NewAPIPathParameterError(parameter string, parameterError error) error

NewAPIPathParameterError returns a new path parameter error.

Call this any time there is any issue at all with a path parameter. For example, if it is required but missing; if it has an incorrect value; or if it needed to be parsed and could not be parsed.

func NewAPIQueryParameterError

func NewAPIQueryParameterError(parameter string, parameterError error) error

NewAPIQueryParameterError returns a new query parameter error.

Call this any time there is any issue at all with a query parameter. For example, if it is required but missing; if it has an incorrect value; or if it needed to be parsed and could not be parsed.

func NewAPIResponseError

func NewAPIResponseError(code int, message string) error

NewAPIResponseError returns a new general API response error.

Whatever HTTP status code was given will be used for the response. An error structure will be rendered with the given message.

If the message is empty, then a default one will be generated based on the HTTP status code.

func Register

func Register(apiTagKey string, f RegisterFunction)

Register a new API tag.

This will panic if the tag is already registered.

Types

type APIBodyError

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

APIBodyError is an error that represents a parsing issue with the POST body in some way.

This will always be a 400-level error.

func (*APIBodyError) Error

func (e *APIBodyError) Error() string

func (*APIBodyError) Unwrap

func (e *APIBodyError) Unwrap() []error

func (*APIBodyError) WriteError

func (e *APIBodyError) WriteError(resp *restful.Response)

type APIHeaderParameterError

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

APIHeaderParameterError is an error that represents a header parameter error.

This will always be a 400-level error.

func (*APIHeaderParameterError) Error

func (e *APIHeaderParameterError) Error() string

func (*APIHeaderParameterError) Unwrap

func (e *APIHeaderParameterError) Unwrap() []error

func (*APIHeaderParameterError) WriteError

func (e *APIHeaderParameterError) WriteError(resp *restful.Response)

type APIHeaderParameterErrorOutput

type APIHeaderParameterErrorOutput struct {
	APIResponseErrorOutput
	Parameter string `json:"parameter"`
}

APIHeaderParameterErrorOutput is the output structure for a header parameter error.

type APIPathParameterError

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

APIPathParameterError is an error that represents a path parameter error.

This will always be a 400-level error.

func (*APIPathParameterError) Error

func (e *APIPathParameterError) Error() string

func (*APIPathParameterError) Unwrap

func (e *APIPathParameterError) Unwrap() []error

func (*APIPathParameterError) WriteError

func (e *APIPathParameterError) WriteError(resp *restful.Response)

type APIPathParameterErrorOutput

type APIPathParameterErrorOutput struct {
	APIResponseErrorOutput
	Parameter string `json:"parameter"`
}

APIPathParameterErrorOutput is the output structure for a path parameter error.

type APIQueryParameterError

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

APIQueryParameterError is an error that represents a query parameter error.

This will always be a 400-level error.

func (*APIQueryParameterError) Error

func (e *APIQueryParameterError) Error() string

func (*APIQueryParameterError) Unwrap

func (e *APIQueryParameterError) Unwrap() []error

func (*APIQueryParameterError) WriteError

func (e *APIQueryParameterError) WriteError(resp *restful.Response)

type APIQueryParameterErrorOutput

type APIQueryParameterErrorOutput struct {
	APIResponseErrorOutput
	Parameter string `json:"parameter"`
}

APIQueryParameterErrorOutput is the output structure for a query parameter error.

type APIResponseError

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

APIResponseError is an error that represents a general HTTP response failure.

This can represent any HTTP error code.

func (*APIResponseError) Code

func (e *APIResponseError) Code() int

Code returns the HTTP status code.

func (*APIResponseError) Error

func (e *APIResponseError) Error() string

func (*APIResponseError) Unwrap

func (e *APIResponseError) Unwrap() error

func (*APIResponseError) WriteError

func (e *APIResponseError) WriteError(resp *restful.Response)

type APIResponseErrorOutput

type APIResponseErrorOutput struct {
	Type    string `json:"type,omitempty"`
	Message string `json:"message"`
}

APIResponseErrorOutput is the output structure for an error.

type ContextAction

type ContextAction func(ctx context.Context, info *RestfulFunctionInfo) context.Context

ContextAction is a context action function.

type ErrorHandler added in v0.1.2

type ErrorHandler func(err error) error

ErrorHandler can be used to translate an error into a different error.

This is useful if you use a custom error type that you want to translate into a particular HTTP status code, for example.

type ErrorWriter

type ErrorWriter interface {
	// WriteError writes the error to the response.
	WriteError(resp *restful.Response)
}

ErrorWriter can be used to implement custom error responses. These could be plain text, JSON, etc.

This package provides a number of built-in error types that implement this interface, but you may implement your own as well.

type HTTPMethodDELETE

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

HTTPMethodDELETE marks this endpoint as DELETE.

type HTTPMethodGET

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

HTTPMethodGET marks this endpoint as GET.

type HTTPMethodOPTIONS

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

HTTPMethodOPTIONS marks this endpoint as OPTIONS.

type HTTPMethodPATCH

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

HTTPMethodPATCH marks this endpoint as PATCH.

type HTTPMethodPOST

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

HTTPMethodPOST marks this endpoint as POST.

type HTTPMethodPUT

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

HTTPMethodPUT marks this endpoint as PUT.

type InputField

type InputField struct {
	Name     string             // This is the name of the field.
	Function InputFieldFunction // This is the function that we will call to set its value.
}

InputField represents a field on the metadata struct.

type InputFieldFunction

type InputFieldFunction func(v reflect.Value, req *restful.Request, metadataValue reflect.Value) error

InputFieldFunction sets the value of the field.

type ParameterParser

type ParameterParser interface {
	// Parse accepts a string and returns an error on failure.
	ParseString(input string) error
}

ParameterParser is an interface that a parameter can implement in order to be eligible for use in query and path parameters.

type RegisterFunction

type RegisterFunction func(apiTagValue string, field reflect.StructField, info *RestfulFunctionInfo) (InputFieldFunction, error)

RegisterFunction is a function that can be used to register a new API tag.

type RestfulFunctionHeaderParameter

type RestfulFunctionHeaderParameter struct {
	FieldName     string
	Name          string
	Description   string
	AllowMultiple bool
}

RestfulFunctionHeaderParameter represents a header parameter.

type RestfulFunctionInfo

type RestfulFunctionInfo struct {
	FunctionValue       reflect.Value // This is the function that will be called.
	InContextPosition   int           // This is the position of the context parameter of the method, if any.
	InMetadataPosition  int           // This is the position of the metadata parameter of the method, if any.
	InMetadataType      reflect.Type  // This is the type of the metadata parameter of the method, if any.
	OutErrorPosition    int           // This is the position of the error return value, if any.
	OutResponsePosition int           // This is the position of the response return value, if any.

	HTTPMethod       string                           // This is the HTTP method.
	HTTPPath         string                           // This is the path (including any "{}" router syntax).
	Doc              string                           // Used with "restful".
	Notes            string                           // Used with "restful".
	PathParameters   []RestfulFunctionPathParameter   // Used with "restful".
	QueryParameters  []RestfulFunctionQueryParameter  // Used with "restful".
	HeaderParameters []RestfulFunctionHeaderParameter // Used with "restful".
	BodyExample      any                              // Used with "restful".
	ResponseExample  any                              // Used with "restful".
	Do               []func(*restful.RouteBuilder)    // Used with "restful"; these will be called as "Do" functions.
	Consumes         []string                         // Used with "restful".
	Produces         []string                         // Used with "restful".

	InputFields []InputField // This is the list of fields in the metadata struct and how we populate them.

	LocalMap map[string]string // This is an arbitrary mapping that can be used to store information.
}

RestfulFunctionInfo contains all of the information about a method that can be used as an endpoint.

func ParseRestfulFunction

func ParseRestfulFunction(f interface{}) (*RestfulFunctionInfo, error)

ParseRestfulFunction accepts a function and returns the parsed information about that function.

This information can be used to generate a function that can be called to handle the given REST request.

func (*RestfulFunctionInfo) CreateFunctionWithError

func (info *RestfulFunctionInfo) CreateFunctionWithError(errorHandler ErrorHandler) RestfulFunctionWithError

CreateFunctionWithError returns a `RestfulFunctionWithError` using the given attributes.

func (*RestfulFunctionInfo) UpdateRouteBuilder

func (info *RestfulFunctionInfo) UpdateRouteBuilder(routeBuilder *restful.RouteBuilder)

UpdateRouteBuilder updates a restful.Routebuilder with the information that we got from parsing the function.

type RestfulFunctionPathParameter

type RestfulFunctionPathParameter struct {
	FieldName   string
	Name        string
	Description string
}

RestfulFunctionPathParameter represents a path parameter.

type RestfulFunctionQueryParameter

type RestfulFunctionQueryParameter struct {
	FieldName     string
	Name          string
	Description   string
	AllowMultiple bool
}

RestfulFunctionQueryParameter represents a query parameter.

type RestfulFunctionWithError

type RestfulFunctionWithError func(req *restful.Request, resp *restful.Response) error

RestfulFunctionWithError is a restful.RouteFunction that returns an error.

type RestfulRouteWrapper

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

RestfulRouteWrapper wraps a route and ultimately will result in a `*restful.RouteBuilder` value.

func (*RestfulRouteWrapper) Consumes

func (r *RestfulRouteWrapper) Consumes(contentTypes ...string) *RestfulRouteWrapper

Consumes sets the content types that will be consumed.

func (*RestfulRouteWrapper) Do

func (r *RestfulRouteWrapper) Do(doFunctions ...func(*restful.RouteBuilder)) *RestfulRouteWrapper

Do registers restful.RouteBuilder functions that will apply to all subsequent Route calls.

func (*RestfulRouteWrapper) Path

Path sets the path.

func (*RestfulRouteWrapper) Produces

func (r *RestfulRouteWrapper) Produces(contentTypes ...string) *RestfulRouteWrapper

Produces sets the content types that will be produced.

func (*RestfulRouteWrapper) RouteBuilder

func (r *RestfulRouteWrapper) RouteBuilder() *restful.RouteBuilder

RouteBuilder returns a RouteBuilder with everything we know so far.

type RestfulWrapper

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

RestfulWrapper is our restful wrapper.

func WebService

func WebService(path string) *RestfulWrapper

WebService creates a new restful.WebService with the given path, but in a wrapper that makes it easy to add routes with common properties.

func (*RestfulWrapper) Attributes

func (r *RestfulWrapper) Attributes(attributes map[string]any) *RestfulWrapper

Attributes sets (adds to) the attributes for any request.

These attributes will be accessible via `restful.Request`'s `Attribute` function.

func (*RestfulWrapper) Consumes

func (r *RestfulWrapper) Consumes(contentTypes ...string) *RestfulWrapper

Consumes sets the content types that will be consumed.

func (*RestfulWrapper) ContextAction

func (w *RestfulWrapper) ContextAction(f ...ContextAction) *RestfulWrapper

func (*RestfulWrapper) DELETE

func (r *RestfulWrapper) DELETE(path string) *RestfulRouteWrapper

DELETE creates a DELETE request (for compatiblity with restful.DELETE).

func (*RestfulWrapper) Do

func (r *RestfulWrapper) Do(doFunctions ...func(*restful.RouteBuilder)) *RestfulWrapper

Do registers restful.RouteBuilder functions that will apply to all subsequent Route calls.

func (*RestfulWrapper) ErrorHandler added in v0.1.2

func (r *RestfulWrapper) ErrorHandler(errorHandler ErrorHandler) *RestfulWrapper

func (*RestfulWrapper) GET

GET creates a GET request (for compatiblity with restful.GET).

func (*RestfulWrapper) Method

func (r *RestfulWrapper) Method(method string) *RestfulRouteWrapper

Method sets the method (for compatibility with restful.Method).

func (*RestfulWrapper) OPTIONS

func (r *RestfulWrapper) OPTIONS(path string) *RestfulRouteWrapper

OPTIONS creates a OPTIONS request (for compatiblity with restful.OPTIONS).

func (*RestfulWrapper) PATCH

func (r *RestfulWrapper) PATCH(path string) *RestfulRouteWrapper

PATCH creates a PATCH request (for compatiblity with restful.PATCH).

func (*RestfulWrapper) POST

func (r *RestfulWrapper) POST(path string) *RestfulRouteWrapper

POST creates a POST request (for compatiblity with restful.POST).

func (*RestfulWrapper) PUT

PUT creates a PUT request (for compatiblity with restful.PUT).

func (*RestfulWrapper) Produces

func (r *RestfulWrapper) Produces(contentTypes ...string) *RestfulWrapper

Produces sets the content types that will be produced.

func (*RestfulWrapper) Register

func (r *RestfulWrapper) Register(ctx context.Context, path string, f any)

Register is the next-generation `To` replacement that accepts a struct pointer with a collection of methods. Each method that _can_ be used as an endpoint will be used as an endpoint.

The path given will be used as the root for any endpoints. Note that the RestfulWrapper itself may already have its own path root; this new path will be appended to that.

func (*RestfulWrapper) Route

func (r *RestfulWrapper) Route(routeBuilders ...*restful.RouteBuilder) *RestfulWrapper

Route adds a number of routes to the restful.WebService.

func (*RestfulWrapper) Session

func (r *RestfulWrapper) Session() *RestfulWrapper

Session returns a new session of the wrapper. Any modifications will not affect the original instance and will only apply to new routes added to this session.

func (*RestfulWrapper) WebService

func (r *RestfulWrapper) WebService() *restful.WebService

WebService returns the underlying restful.WebService for use with the other restful functions.

type Writer

type Writer interface {
	Write(*restful.Response)
}

Writer can be used on an output type to control exactly how a response is rendered.

For example, this can be used to set up a redirect with a "Location" header or render a PDF with a custom "Content-Type".

Jump to

Keyboard shortcuts

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