apirouter

package module
v0.5.27 Latest Latest
Warning

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

Go to latest
Published: Feb 25, 2025 License: MIT Imports: 36 Imported by: 1 module, 11 packages

The first number is the count of modules that contain a package that imports this one. The module count is a better indicator of popularity than the package count. A module with 100 importing packages is counted only once instead of 100 times, reflecting the fact that the choice to use the package was likely made only once, not 100 times.
A '?' means that the value hasn't been computed yet.

README

GoDoc

API router

Returning errors

When returning an error, it is good practice to use the Error object.

User

Setting up a request hook that will check the authorization header and call Context.SetUser allows passing an object to other methods.

Documentation

Index

Constants

View Source
const (
	MaxJsonDataLength       = int64(10<<20) + 1 // JSON max body size = 10MB
	MaxUrlEncodedDataLength = int64(1<<20) + 1  // urlencoded max body size = 1MB
	MaxMultipartFormLength  = int64(1<<28) + 1  // multipart form max size = 256MB
)

Variables

View Source
var (
	ErrTargetMissing         = errors.New("missing target")
	ErrNotFound              = &Error{Message: "Not found", Token: "error_not_found", Code: http.StatusNotFound, parent: fs.ErrNotExist}
	ErrAccessDenied          = &Error{Message: "Access denied", Token: "error_access_denied", Code: http.StatusForbidden}
	ErrInternal              = &Error{Message: "An internal error occured", Token: "error_internal", Code: http.StatusInternalServerError}
	ErrInsecureRequest       = &Error{Message: "Request must use POST and have the appropriate tokens", Token: "error_insecure_request", Code: http.StatusBadRequest}
	ErrTeapot                = &Error{Message: "A teapot has appeared", Token: "error_teapot", Code: http.StatusTeapot}
	ErrLengthRequired        = &Error{Message: "Content-Length header is required for this request", Token: "error_length_required", Code: http.StatusLengthRequired}
	ErrRequestEntityTooLarge = &Error{Message: "Request body is too large", Token: "error_request_entity_too_large", Code: http.StatusRequestEntityTooLarge}
)
View Source
var (
	RequestHooks  []RequestHook
	ResponseHooks []ResponseHook
)
View Source
var HTTP = http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
	ctx, err := NewHttp(rw, req)
	if err != nil {
		res := ctx.errorResponse(err)
		res.ServeHTTP(rw, req)
		return
	}
	res, _ := ctx.Response()
	res.ServeHTTP(rw, req)
})

apirouter.HTTP can be used both as a handler function, or as a handler.

Functions

func BroadcastJson added in v0.5.8

func BroadcastJson(ctx context.Context, data any) error

BroadcastJson sends a message to ALL peers connected to the json socket. It should be formatted with at least something similar to: map[string]any{"result": "event", "data": ...}

func BroadcastWS added in v0.4.4

func BroadcastWS(ctx context.Context, data any) error

BroadcastWS sends a message to ALL peers connected to the websocket. It should be formatted with at least something similar to: map[string]any{"result": "event", "data": ...}

func CSRFHeaderHook added in v0.1.8

func CSRFHeaderHook(c *Context) error

CSRFHeaderHook is a sample hook for checking a specific middleware header for csrf validation

func GetDomainForRequest added in v0.2.14

func GetDomainForRequest(req *http.Request) string

GetDomainForRequest will return the domain for a given http.Request, handling cases with redirects

func GetHeader added in v0.0.15

func GetHeader(ctx context.Context, hdr string) string

GetHeader returns the requested header or an empty string if not found

func GetInputJSON added in v0.1.11

func GetInputJSON[T ~[]byte](ctx context.Context) T

func GetObject added in v0.1.6

func GetObject[T any](ctx context.Context, typ string) *T

GetObject fetches an object associated with the context and casts it

func GetParam added in v0.1.8

func GetParam[T any](ctx context.Context, v string) (T, bool)

GetParam returns the parameter specified, and a boolean representing whether the value could be found and was of the right type

func GetParamDefault added in v0.5.20

func GetParamDefault[T any](ctx context.Context, v string, def T) T

GetParamDefault works the same as GetParam, except def will be returned if the value is not specified or fails to be converted to the needed type.

func GetPrefixForRequest added in v0.2.14

func GetPrefixForRequest(req *http.Request) *url.URL

GetPrefixForRequest can be used to obtain the prefix for a given request and will be able to address the local server directly. It'll handle Sec-Original-Host and Sec-Access-Prefix headers

func GetRequestBody added in v0.0.15

func GetRequestBody(ctx context.Context) (io.ReadCloser, error)

GetRequestBody returns the current request's body if any, or an error

func GetUser added in v0.1.8

func GetUser[T any](ctx context.Context) *T

GetUser will return the user object if it matches type T. If there is no user object or it is not of the right type, nil will be returned

func MakeJsonSocketFD added in v0.5.8

func MakeJsonSocketFD(extraObjects map[string]any) (int, error)

MakeJsonSocketFD returns a file descriptor (integer) for a new json socket

func MakeJsonUnixListener added in v0.5.8

func MakeJsonUnixListener(socketName string, extraObjects map[string]any) error

MakeJsonUnixListener creates a UNIX socket at the given path and listen to it, initializing a json socket for each connection. It uses some tricks if socketName is too long, since there is a 104 chars limits on darwin and 108 chars limit on linux

func Progress added in v0.5.6

func Progress(ctx context.Context, data any) error

Progress sends progress through the context response sink

func SecurePost added in v0.1.7

func SecurePost(ctx context.Context) error

SecurePost ensures request was a POST request and has the required headers

func SendWS added in v0.5.23

func SendWS(ctx context.Context, channel string, data any) error

func SetExtraResponse added in v0.5.14

func SetExtraResponse(ctx context.Context, k string, v any) bool

SetExtraResponse adds response data to be added in the final response as meta-data, such as for paging, audit trails, etc

If the context cannot be retrieved this will return false

func WithObject added in v0.5.13

func WithObject(h http.Handler, typ string, obj any) http.HandlerFunc

WithObject can be used to add an object to the generated context, that can then be obtained via apirouter.GetObject(ctx, ...).

func WithValue added in v0.5.13

func WithValue(h http.Handler, key, val any) http.HandlerFunc

WithValue is a method that can be used to add a value to the context of all requests going through a handler. This will automatically call context.WithValue on all incoming requests.

Types

type Context

type Context struct {
	context.Context
	// contains filtered or unexported fields
}

func New

func New(ctx context.Context, path, verb string) *Context

New instanciates a new Context with the given path and verb

func NewChild added in v0.4.0

func NewChild(parent *Context, req []byte, contentType string) (*Context, error)

NewChild instanciates a new Context for a given child request. req will be a json or cbor object containing: path, verb (default=GET), params

func NewHttp

func NewHttp(rw http.ResponseWriter, req *http.Request) (*Context, error)

func (*Context) Call

func (c *Context) Call() (any, error)

func (*Context) CallSpecial

func (c *Context) CallSpecial() (any, error)

func (*Context) GetDomain added in v0.0.10

func (c *Context) GetDomain() string

GetDomain returns the domain on which the request was issued

func (*Context) GetExtraResponse added in v0.0.6

func (c *Context) GetExtraResponse(k string) any

GetExtraResponse returns the extra response data that was previously set

func (*Context) GetListen added in v0.5.21

func (c *Context) GetListen() []string

func (*Context) GetObject added in v0.0.3

func (c *Context) GetObject(typ string) any

GetObject fetches an object associated with the current request

func (*Context) GetParam

func (c *Context) GetParam(v string) any

GetParam returns one individual value from the current parameters, and can lookup valuyes in submaps/etc by adding a dot between values.

func (*Context) GetParamTo

func (c *Context) GetParamTo(v string, obj any) error

GetParamTo assigns the given GET param to an object, converting the type if needed

func (*Context) GetParams

func (c *Context) GetParams() map[string]any

GetParams returns all the parameters associated with this request

func (*Context) GetPath

func (c *Context) GetPath() string

GetPath returns the API path that was requested

func (*Context) GetQuery added in v0.0.5

func (c *Context) GetQuery(v string) any

GetQuery returns a value from the GET parameters passed to the API

func (*Context) GetQueryFull added in v0.0.8

func (c *Context) GetQueryFull() map[string]any

GetQueryFull returns the whole query string as a map

func (*Context) ListensFor added in v0.5.16

func (c *Context) ListensFor(ev string) bool

func (*Context) NewRequest

func (c *Context) NewRequest(target string) (*http.Request, error)

NewRequest returns a http request for this context (for example for forwarding, etc)

func (*Context) Paginate added in v0.5.7

func (ctx *Context) Paginate(resultsPerPage int) func(tx *gorm.DB) *gorm.DB

Paginate applies standard page_no & results_per_page rules on a gorm tx as a scope

func (*Context) RemoteAddr added in v0.3.7

func (c *Context) RemoteAddr() string

RemoteAddr returns the remote address that made the request, if any is found

func (*Context) RequestId added in v0.0.20

func (c *Context) RequestId() string

RequestId returns the current request's ID, typically a uuid

func (*Context) Response

func (c *Context) Response() (res *Response, err error)

Response executes the request and generates a response object

func (*Context) ServeHTTP

func (c *Context) ServeHTTP(rw http.ResponseWriter, req *http.Request)

func (*Context) SetBytes added in v0.5.3

func (c *Context) SetBytes(req []byte, contentType string) error

SetBytes configures the Context with the given request sent raw with a content type

func (*Context) SetCache added in v0.5.3

func (c *Context) SetCache(t time.Duration)

SetCache defines this API call can be cached up to the given time. A negative or zero value will disable caching (default)

func (*Context) SetCsrfValidated added in v0.1.8

func (c *Context) SetCsrfValidated(ok bool)

SetCsrfValidated is to be used in request hook to tell apirouter if the request came with a valid and appropriate CSRF token.

func (*Context) SetDecoder added in v0.5.3

func (c *Context) SetDecoder(dec interface{ Decode(any) error }) error

SetDecoder sets Context value based on a standardized encoded object to be decoded via an object similar to encoding/json.Decoder.

func (*Context) SetExtraResponse added in v0.0.6

func (c *Context) SetExtraResponse(k string, v any)

SetExtraResponse adds response data to be added in the final response as meta-data, such as for paging, audit trails, etc

func (*Context) SetFlag added in v0.2.9

func (c *Context) SetFlag(flag string, val bool)

SetFlag sets a flag on the context, and should only be used for very specific cases

func (*Context) SetHttp

func (c *Context) SetHttp(rw http.ResponseWriter, req *http.Request) error

SetHttp configures the Context with the given http request and response writer

func (*Context) SetListen added in v0.5.16

func (c *Context) SetListen(ev string, listen bool)

func (*Context) SetObject added in v0.5.5

func (c *Context) SetObject(typ string, v any)

SetObject allows setting an object to be associated with the context for this request

func (*Context) SetParam

func (c *Context) SetParam(name string, v any)

SetParam allows setting one individual parameter to the request

func (*Context) SetParams

func (c *Context) SetParams(v map[string]any)

SetParams sets the params passed to the API

func (*Context) SetPath

func (c *Context) SetPath(p string)

func (*Context) SetResponseSink added in v0.5.6

func (c *Context) SetResponseSink(sink ResponseSink)

SetResponseSink sets the context's response sink used to send intermediate progress reports

func (*Context) SetShowProtectedFields added in v0.3.6

func (c *Context) SetShowProtectedFields(p bool)

SetShowProtectedFields allows defining if fields flagged as protected should be shown or not

func (*Context) SetUser added in v0.1.8

func (c *Context) SetUser(user any)

SetUser sets the user object for the associated context, which can be fetched with GetUser[T](ctx). This method will typically be called in a RequestHook.

func (*Context) Value

func (c *Context) Value(v any) any

type Deletable added in v0.0.4

type Deletable interface {
	ApiDelete(ctx *Context) error
}

type EncoderInterface added in v0.5.6

type EncoderInterface interface {
	Encode(obj any) error
}

type Error added in v0.0.17

type Error struct {
	Message string // error message
	Code    int    // HTTP status code for error
	Token   string // optional error token
	Info    any    // optional extra information for the error
	// contains filtered or unexported fields
}

func ErrBadRequest added in v0.2.6

func ErrBadRequest(token, msg string, args ...any) *Error

ErrBadRequest is a helper returning an error with code StatusBadRequest

func ErrForbidden added in v0.2.6

func ErrForbidden(token, msg string, args ...any) *Error

Forbidden is a helper returning an error with code StatusForbidden

func ErrInternalServerError added in v0.2.6

func ErrInternalServerError(token, msg string, args ...any) *Error

func ErrMethodNotAllowed added in v0.2.6

func ErrMethodNotAllowed(token, msg string, args ...any) *Error

func ErrNotImplemented added in v0.2.6

func ErrNotImplemented(token, msg string, args ...any) *Error

func ErrServiceUnavailable added in v0.2.6

func ErrServiceUnavailable(token, msg string, args ...any) *Error

func NewError added in v0.2.6

func NewError(code int, token, msg string, args ...any) *Error

func (*Error) Error added in v0.0.17

func (e *Error) Error() string

func (*Error) HTTPStatus added in v0.0.17

func (e *Error) HTTPStatus() int

func (*Error) Unwrap added in v0.2.6

func (e *Error) Unwrap() error

type RequestHook added in v0.0.20

type RequestHook func(c *Context) error

type Response

type Response struct {
	Result       string  `json:"result"` // error|success|redirect
	Error        string  `json:"error,omitempty"`
	Token        string  `json:"token,omitempty"`
	ErrorInfo    any     `json:"error_info,omitempty"`
	Code         int     `json:"code,omitempty"`
	Debug        string  `json:"debug,omitempty"`
	RequestId    string  `json:"request_id,omitempty"`
	Time         float64 `json:"time"`
	Data         any     `json:"data"`
	RedirectURL  string  `json:"redirect_url,omitempty"`
	RedirectCode int     `json:"redirect_code,omitempty"`
	QueryId      any     `json:"query_id,omitempty"`
	// contains filtered or unexported fields
}

func (*Response) GetContext added in v0.1.13

func (r *Response) GetContext() *Context

func (*Response) MarshalContextJSON added in v0.5.4

func (r *Response) MarshalContextJSON(ctx context.Context) ([]byte, error)

func (*Response) MarshalJSON added in v0.5.4

func (r *Response) MarshalJSON() ([]byte, error)

func (*Response) ServeHTTP

func (r *Response) ServeHTTP(rw http.ResponseWriter, req *http.Request)

type ResponseHook added in v0.0.20

type ResponseHook func(r *Response) error

type ResponseSink added in v0.5.6

type ResponseSink interface {
	SendResponse(*Response) error
}

func EncoderSink added in v0.5.6

func EncoderSink(enc EncoderInterface) ResponseSink

type Updatable added in v0.0.4

type Updatable interface {
	ApiUpdate(ctx *Context) error
}

Jump to

Keyboard shortcuts

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