routing

package
v0.0.39 Latest Latest
Warning

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

Go to latest
Published: Mar 31, 2024 License: MIT Imports: 14 Imported by: 0

Documentation

Index

Constants

View Source
const (
	StatusContinue           = 100 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/100
	StatusSwitchingProtocols = 101 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/101
	StatusProcessing         = 102 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/102
	StatusEarlyHints         = 103 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/103

	StatusOk                   = 200 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/200
	StatusCreated              = 201 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/201
	StatusAccepted             = 202 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/202
	StatusNonAuthoritativeInfo = 203 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/203
	StatusNoContent            = 204 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/204
	StatusResetContent         = 205 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/205
	StatusPartialContent       = 206 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/206
	StatusMultiStatus          = 207 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/207
	StatusAlreadyReported      = 208 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/208
	StatusIMUsed               = 226 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/226

	StatusMultipleChoices   = 300 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/300
	StatusMovedPermanently  = 301 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/301
	StatusFound             = 302 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/302
	StatusSeeOther          = 303 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/303
	StatusNotModified       = 304 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/304
	StatusTemporaryRedirect = 307 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/307
	StatusPermanentRedirect = 308 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/308

	StatusBadRequest                   = 400 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/400
	StatusUnauthorized                 = 401 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/401
	StatusPaymentRequired              = 402 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/402
	StatusForbidden                    = 403 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/403
	StatusNotFound                     = 404 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/404
	StatusMethodNotAllowed             = 405 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/405
	StatusNotAcceptable                = 406 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/406
	StatusProxyAuthRequired            = 407 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/407
	StatusRequestTimeout               = 408 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/408
	StatusConflict                     = 409 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/409
	StatusGone                         = 410 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/410
	StatusLengthRequired               = 411 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/411
	StatusPreconditionFailed           = 412 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/412
	StatusRequestEntityTooLarge        = 413 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/413
	StatusRequestURITooLong            = 414 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/414
	StatusUnsupportedMediaType         = 415 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/415
	StatusRequestedRangeNotSatisfiable = 416 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/416
	StatusExpectationFailed            = 417 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/417
	StatusTeapot                       = 418 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/418
	StatusMisdirectedRequest           = 421 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/421
	StatusUnprocessableEntity          = 422 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/422
	StatusLocked                       = 423 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/423
	StatusFailedDependency             = 424 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/424
	StatusTooEarly                     = 425 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/425
	StatusUpgradeRequired              = 426 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/426
	StatusPreconditionRequired         = 428 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/428
	StatusTooManyRequests              = 429 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/429
	StatusRequestHeaderFieldsTooLarge  = 431 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/431
	StatusUnavailableForLegalReasons   = 451 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/451

	StatusInternalServerError           = 500 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/500
	StatusNotImplemented                = 501 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/501
	StatusBadGateway                    = 502 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/502
	StatusServiceUnavailable            = 503 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/503
	StatusGatewayTimeout                = 504 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/504
	StatusHTTPVersionNotSupported       = 505 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/505
	StatusVariantAlsoNegotiates         = 506 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/506
	StatusInsufficientStorage           = 507 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/507
	StatusLoopDetected                  = 508 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/508
	StatusNotExtended                   = 510 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/510
	StatusNetworkAuthenticationRequired = 511 // See: https://developer.mozilla.org/en-US/docs/Web/HTTP/Status/511
)

Variables

This section is empty.

Functions

func GetBody added in v0.0.25

func GetBody[TBody any](s *Store) (value TBody, err error)

Returns the request body marshalled into the given type.

Types

type ApiOptions

type ApiOptions struct {
	Middleware []Middleware
}

ApiOptions defines options to use for a certain endpoint group.

func NoMiddleware

func NoMiddleware() ApiOptions

func WithMiddleware

func WithMiddleware(middleware ...Middleware) ApiOptions

WithMiddleware creates a new ApiOptions instance with all provided middlewares.

type BaseApi

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

BaseApi is the base struct for all goApiRouting functions.

func (*BaseApi) Any added in v0.0.25

func (api *BaseApi) Any(route string, handler func(c *Context) Response)

Any is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle("*", ...)`. Any adds a new endpoint with the provided route and handler for all methods.

func (*BaseApi) Delete

func (api *BaseApi) Delete(route string, handler func(c *Context) Response)

Delete is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodDelete, ...)`. Delete adds a new DELETE endpoint with the provided route and handler.

func (*BaseApi) Get

func (api *BaseApi) Get(route string, handler func(c *Context) Response)

Get is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodGet, ...)`. Get adds a new GET endpoint with the provided route and handler.

func (*BaseApi) Group

func (api *BaseApi) Group(route string, options ApiOptions, group func(api BaseApi))

Group defines a new route group with the provided route, and options. Use the function within the define sub routes for the Group.

func (*BaseApi) Handle

func (api *BaseApi) Handle(method string, route string, handler func(*Context) Response)

Handle adds a new api endpoint with the provided method, route, and handler.

func (*BaseApi) Head

func (api *BaseApi) Head(route string, handler func(c *Context) Response)

HEAD is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodHead, ...)`. HEAD adds a new HEAD endpoint with the provided route and handler.

func (*BaseApi) NoMiddleware

func (*BaseApi) NoMiddleware() ApiOptions

NoMiddleware returns an empty ApiOptions struct.

func (*BaseApi) Options added in v0.0.25

func (api *BaseApi) Options(route string, handler func(c *Context) Response)

OPTIONS is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodOptions, ...)`. OPTIONS adds a new OPTIONS endpoint with the provided route and handler.

func (*BaseApi) Patch

func (api *BaseApi) Patch(route string, handler func(c *Context) Response)

Patch is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodPatch, ...)`. Patch adds a new PATCH endpoint with the provided route and handler.

func (*BaseApi) Post

func (api *BaseApi) Post(route string, handler func(c *Context) Response)

Post is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodPost, ...)`. Post adds a new POST endpoint with the provided route and handler.

func (*BaseApi) Put added in v0.0.25

func (api *BaseApi) Put(route string, handler func(c *Context) Response)

PUT is a shorthand function for Handle. It has the same functionality as if the user ran `api.Handle(http.MethodPut, ...)`. PUT adds a new PUT endpoint with the provided route and handler.

type Config

type Config struct {
	// The port to listen on. If not provided, will default to :80
	Port int
	// BaseResponseHeaders are the headers to apply to every response.
	//
	// These values can be overwriten in [Response.Headers]
	//
	// [Response.Headers]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Headers
	BaseResponseHeaders map[string]string
	// MaxContentLength is the maximum size of the request body in bytes. Set to 0 to disable.
	//
	// Disabled by default
	MaxContentLength int64
}

Config provides the required config options to the Setup function.

type Context

type Context struct {
	// The request object.
	Request *http.Request
	// The response writer object.
	// Using this may lead to unexpected behaviour.
	Writer http.ResponseWriter
	// The store object.
	Store *Store
}

func (*Context) ServeFile

func (context *Context) ServeFile(path string) Response

type File added in v0.0.29

type File struct {
	Name     string
	FileName string
	FilePath string
	// contains filtered or unexported fields
}

func (*File) Save added in v0.0.29

func (f *File) Save() error

func (*File) Store added in v0.0.29

func (f *File) Store() (string, error)

type InternalServerError added in v0.0.25

type InternalServerError error

type MethodNotSupportedError

type MethodNotSupportedError error

type Middleware

type Middleware = func(c *Context, respond func(Response)) bool

Middleware is a function that runs prior to the main function defined for an endpoint. Use the provided *Context to run all required checks. Return true to run the next function. If false is returned, response must be set within the middleware.

type NotFoundError

type NotFoundError error

type Response

type Response struct {
	// The status code for the response. Defaults to "500 Internal Server Error" unless specified in Setup Config
	Status int
	// The template to use for the response. Only used if [Type] is [HTMLResponse] or [PlainTextResponse]
	Template Template
	// The response body.
	Body interface{}
	// See [JSONResponse], [HTMLResponse], [XMLResponse], [FileResponse], [PlainTextResponse], [RedirectResponse], [NoResponse], [CustomResponse]
	Type ResponseType
	// The headers to add to the response.
	Headers map[string]string
}

type ResponseType

type ResponseType string
const (
	// JSONResponse is used in [Response.Type] to instruct the router to use [json.Marshal] to format the body.
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	// [json.Marshal]: https://pkg.go.dev/encoding/json#Marshal
	JSONResponse ResponseType = "application/json"

	// HTMLResponse is used in [Response.Type] to instruct the router to return the body as a plain string.
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	HTMLResponse ResponseType = "text/html"

	// XMLResponse is used in [Response.Type] to instruct the router to use [encoding/xml.Marshal] to format the [Response.Body].
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	// [json.Marshal]: https://pkg.go.dev/encoding/xml#Marshal
	XMLResponse ResponseType = "application/xml"

	// PlainTextResponse is used in [Response.Type] to instruct the router to return the body as plain text.
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	PlainTextResponse ResponseType = "text/plain"

	// FileResponse is used in [Response.Type] to serve a file in the response using [http.ServeFile].
	//
	// Provide the path to the file in the [Response.Body].
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	// [Response.Body]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Body
	// [http.ServeFile]: https://pkg.go.dev/net/http#ServeFile
	FileResponse ResponseType = "file"

	// RedirectResponse is used in [Response.Type] to redirect the user to another page.
	//
	// Provide the URL to redirect to in the [Response.Body].
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	// [Response.Body]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Body
	RedirectResponse ResponseType = "redirect"

	// NoResponse is used in [Response.Type] to instruct the router to not write a response.
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	NoResponse ResponseType = "none"

	// CustomResponse is used in [Response.Type] to instruct the router to use a custom function to write the response.
	//
	// Provide the function in the [Response.Body].
	//
	// [Response.Type]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Type
	// [Response.Body]: https://pkg.go.dev/github.com/AubreeH/goApiRouting/routing#Response.Body
	CustomResponse ResponseType = "custom"
)

type Router

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

func NewRouter

func NewRouter(conf ...Config) *Router

NewRouter creates a new router instance with the provided config. Only the first config provided will be used. If no config is provided, the default config will be used. Alias for Setup.

func Setup

func Setup(conf ...Config) *Router

Setup creates a new router instance with the provided config. Only the first config provided will be used. If no config is provided, the default config will be used.

func (*Router) AddRoute added in v0.0.25

func (r *Router) AddRoute(path, method string, handler func(*Context, func(Response)))

func (*Router) InitialiseRoutes

func (r *Router) InitialiseRoutes(apiFuncs ...func(api BaseApi))

InitialiseRoutes initialises all routes defined within the provided functions.

func (*Router) Start

func (r *Router) Start() error

type Store added in v0.0.25

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

func (*Store) Get added in v0.0.25

func (s *Store) Get(key string) (value interface{}, err error)

Retrieves value from the store. The order of precedence is: 1. Store 2. Path parameters 3. Query parameters 4. Body Returns an error if the key is not found.

func (*Store) GetBody added in v0.0.25

func (s *Store) GetBody() (value map[string]interface{}, err error)

Returns the request body as a map.

func (*Store) GetFile added in v0.0.30

func (s *Store) GetFile(key string) (value []*File, ok bool)

func (*Store) GetFiles added in v0.0.30

func (s *Store) GetFiles() map[string][]*File

func (*Store) GetPathParameter added in v0.0.25

func (s *Store) GetPathParameter(key string) (value string, ok bool)

Retrieves path parameter with the given key.

func (*Store) GetQueryParameter added in v0.0.25

func (s *Store) GetQueryParameter(key string) (value []string, ok bool)

Retrieves query parameter with the given key.

func (*Store) Set added in v0.0.28

func (c *Store) Set(key string, value interface{})

Sets value in the store.

type Template added in v0.0.33

type Template interface {
	Execute(w io.Writer, data any) error
}

Jump to

Keyboard shortcuts

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