Documentation
¶
Index ¶
- Variables
- func ErrorMapping(ctx context.Context, err error, dto *rfc7807.DTO)
- func Mount(mux Multiplexer, pattern string, handler http.Handler)
- func MountPoint(mountPoint string, next http.Handler) http.Handler
- func PathParams(ctx context.Context) map[string]string
- func WithMiddleware(handler http.Handler, ffns ...MiddlewareFactoryFunc) http.Handler
- func WithPathParam(ctx context.Context, key, val string) context.Context
- func WithRoundTripper(transport http.RoundTripper, rts ...RoundTripperFactoryFunc) http.RoundTripper
- type AccessLog
- type ClientErrUnexpectedResponse
- type DTOMapping
- type ErrorHandler
- type IDConverter
- type IDInContext
- type IntID
- type Mapping
- type MiddlewareFactoryFunc
- type Multiplexer
- type RestClient
- func (r RestClient[Entity, ID]) Create(ctx context.Context, ptr *Entity) error
- func (r RestClient[Entity, ID]) DeleteAll(ctx context.Context) error
- func (r RestClient[Entity, ID]) DeleteByID(ctx context.Context, id ID) error
- func (r RestClient[Entity, ID]) FindAll(ctx context.Context) iterators.Iterator[Entity]
- func (r RestClient[Entity, ID]) FindByID(ctx context.Context, id ID) (ent Entity, found bool, err error)
- func (r RestClient[Entity, ID]) Update(ctx context.Context, ptr *Entity) error
- type RestClientSerializer
- type RestResource
- type RestResourceSerialization
- type RetryRoundTripper
- type RoundTripperFactoryFunc
- type RoundTripperFunc
- type Router
- func (router *Router) Connect(path string, handler http.Handler)
- func (router *Router) Delete(path string, handler http.Handler)
- func (router *Router) Get(path string, handler http.Handler)
- func (router *Router) Handle(pattern string, handler http.Handler)
- func (router *Router) Head(path string, handler http.Handler)
- func (router *Router) Mount(path string, handler http.Handler)
- func (router *Router) Namespace(path string, blk func(r *Router))
- func (router *Router) On(method, path string, handler http.Handler)
- func (router *Router) Options(path string, handler http.Handler)
- func (router *Router) Patch(path string, handler http.Handler)
- func (router *Router) Post(path string, handler http.Handler)
- func (router *Router) Put(path string, handler http.Handler)
- func (router *Router) Resource(identifier string, resource resource)
- func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (router *Router) Trace(path string, handler http.Handler)
- func (router *Router) Use(mws ...MiddlewareFactoryFunc)
- type Serializer
- type SerializerDefault
- type StringID
Examples ¶
Constants ¶
This section is empty.
Variables ¶
var DefaultBodyReadLimit int = 16 * iokit.Megabyte
DefaultBodyReadLimit is the maximum number of bytes that a restapi.Handler will read from the requester, if the Handler.BodyReadLimit is not provided.
var DefaultResourceClientHTTPClient http.Client = http.Client{ Transport: RetryRoundTripper{ RetryStrategy: retry.ExponentialBackoff{ WaitTime: time.Second, Timeout: time.Minute, }, }, Timeout: 25 * time.Second, }
var DefaultSerializer = SerializerDefault{ Serializer: serializers.JSON{}, MIMEType: "application/json", }
var DefaultSerializers = map[string]Serializer{ "application/json": serializers.JSON{}, "application/problem+json": serializers.JSON{}, "application/x-ndjson": serializers.JSONStream{}, "application/stream+json": serializers.JSONStream{}, "application/json-stream": serializers.JSONStream{}, "application/x-www-form-urlencoded": serializers.FormURLEncoder{}, }
var ErrEntityAlreadyExist = errorkit.UserError{
ID: "entity-already-exists",
Message: "The entity could not be created as it already exists.",
}
var ErrEntityNotFound = errorkit.UserError{
ID: "entity-not-found",
Message: "The requested entity is not found in this resource.",
}
var ErrInternalServerError = errorkit.UserError{
ID: "internal-server-error",
Message: "An unexpected internal server error occurred.",
}
var ErrInvalidRequestBody = errorkit.UserError{
ID: "invalid-request-body",
Message: "The request body is invalid.",
}
var ErrMalformedID = errorkit.UserError{
ID: "malformed-id-in-path",
Message: "The received entity id in the path is malformed.",
}
var ErrMethodNotAllowed = errorkit.UserError{
ID: "restapi-method-not-allowed",
Message: "The requested RESTful method is not supported.",
}
var ErrPathNotFound = errorkit.UserError{
ID: "path-not-found",
Message: "The requested path is not found.",
}
var ErrRequestEntityTooLarge = errorkit.UserError{
ID: "request-entity-too-large",
Message: "The request body was larger than the size limit allowed for the server.",
}
Functions ¶
func ErrorMapping ¶ added in v0.220.0
func Mount ¶ added in v0.187.0
func Mount(mux Multiplexer, pattern string, handler http.Handler)
Mount will help to register a handler on a request multiplexer in both as the concrete path to the handler and as a prefix match. example:
if pattern -> "/something" registered as "/something" for exact match registered as "/something/" for prefix match
Example ¶
package main import ( "net/http" "go.llib.dev/frameless/pkg/httpkit" ) func main() { var ( apiV0 http.Handler webUI http.Handler mux = http.NewServeMux() ) httpkit.Mount(mux, "/api/v0", apiV0) httpkit.Mount(mux, "/ui", webUI) }
func MountPoint ¶ added in v0.220.0
func WithMiddleware ¶ added in v0.211.0
func WithMiddleware(handler http.Handler, ffns ...MiddlewareFactoryFunc) http.Handler
WithMiddleware will combine an http.Handler with a stack of middleware factory functions. The order in which you pass the MiddlewareFactoryFunc -s is the same as the order, they will be called during the http.Handler.ServeHTTP method call.
func WithPathParam ¶ added in v0.220.0
func WithRoundTripper ¶ added in v0.216.0
func WithRoundTripper(transport http.RoundTripper, rts ...RoundTripperFactoryFunc) http.RoundTripper
WithRoundTripper will combine an http.RoundTripper with a stack of middleware factory functions. The execution order is in which you pass the factory funcs.
Example ¶
package main import ( "net/http" "go.llib.dev/frameless/pkg/httpkit" ) func main() { transport := httpkit.WithRoundTripper(nil, func(next http.RoundTripper) http.RoundTripper { return httpkit.RoundTripperFunc(func(request *http.Request) (*http.Response, error) { request.Header.Set("Authorization", "<type> <credentials>") return next.RoundTrip(request) }) }) _ = &http.Client{ Transport: transport, } }
Types ¶
type AccessLog ¶
type ClientErrUnexpectedResponse ¶ added in v0.220.0
func (ClientErrUnexpectedResponse) Error ¶ added in v0.220.0
func (err ClientErrUnexpectedResponse) Error() string
type DTOMapping ¶ added in v0.220.0
type DTOMapping[Entity, DTO any] struct { // ToEnt is an optional function to describe how to map a DTO into an Entity. // // default: dtokit.Map[Entity, DTO](...) ToEnt func(ctx context.Context, dto DTO) (Entity, error) // ToDTO is an optional function to describe how to map an Entity into a DTO. // // default: dtokit.Map[DTO, Entity](...) ToDTO func(ctx context.Context, ent Entity) (DTO, error) }
DTOMapping is a type safe implementation for the generic Mapping interface. When using the frameless/pkg/dtos package, all you need to provide is the type arguments; nothing else is required.
type ErrorHandler ¶ added in v0.220.0
type ErrorHandler interface {
HandleError(w http.ResponseWriter, r *http.Request, err error)
}
type IDConverter ¶ added in v0.220.0
IDConverter is an OldMapping tool that you can embed in your OldMapping implementation, and it will implement the ID encoding that will be used in the URL.
func (IDConverter[ID]) FormatID ¶ added in v0.220.0
func (m IDConverter[ID]) FormatID(id ID) (string, error)
func (IDConverter[ID]) ParseID ¶ added in v0.220.0
func (m IDConverter[ID]) ParseID(data string) (ID, error)
type IDInContext ¶ added in v0.220.0
type IDInContext[CtxKey, EntityIDType any] struct{}
IDInContext is an OldMapping tool that you can embed in your OldMapping implementation, and it will implement the context handling related methods.
func (IDInContext[CtxKey, EntityIDType]) ContextLookupID ¶ added in v0.220.0
func (cm IDInContext[CtxKey, EntityIDType]) ContextLookupID(ctx context.Context) (EntityIDType, bool)
func (IDInContext[CtxKey, EntityIDType]) ContextWithID ¶ added in v0.220.0
func (cm IDInContext[CtxKey, EntityIDType]) ContextWithID(ctx context.Context, id EntityIDType) context.Context
type IntID ¶ added in v0.220.0
type IntID[ID ~int] struct{}
IntID is an OldMapping tool that you can embed in your OldMapping implementation, and it will implement the ID encoding that will be used in the URL.
type Mapping ¶ added in v0.220.0
type Mapping[Entity any] interface { // contains filtered or unexported methods }
Mapping is a generic interface used for representing a DTO-Entity mapping relationship. Its primary function is to allow Resource to list various mappings, each with its own DTO type, for different MIMEType values. This means we can use different DTO types within the same restful Resource handler based on different content types, making it more flexible and adaptable to support different Serialization formats.
It is implemented by DTOMapping.
type MiddlewareFactoryFunc ¶ added in v0.211.0
MiddlewareFactoryFunc is a constructor function that is meant to wrap an http.Handler with given middleware. Its http.Handler argument represents the next middleware http.Handler in the pipeline.
type Multiplexer ¶ added in v0.211.0
Multiplexer represents a http request Multiplexer.
type RestClient ¶ added in v0.220.0
type RestClient[Entity, ID any] struct { BaseURL string HTTPClient *http.Client MIMEType string Mapping Mapping[Entity] Serializer RestClientSerializer IDConverter idConverter[ID] LookupID crud.LookupIDFunc[Entity, ID] }
func (RestClient[Entity, ID]) Create ¶ added in v0.220.0
func (r RestClient[Entity, ID]) Create(ctx context.Context, ptr *Entity) error
func (RestClient[Entity, ID]) DeleteAll ¶ added in v0.220.0
func (r RestClient[Entity, ID]) DeleteAll(ctx context.Context) error
func (RestClient[Entity, ID]) DeleteByID ¶ added in v0.220.0
func (r RestClient[Entity, ID]) DeleteByID(ctx context.Context, id ID) error
func (RestClient[Entity, ID]) FindAll ¶ added in v0.220.0
func (r RestClient[Entity, ID]) FindAll(ctx context.Context) iterators.Iterator[Entity]
type RestClientSerializer ¶ added in v0.220.0
type RestClientSerializer interface { serializers.Serializer serializers.ListDecoderMaker }
type RestResource ¶ added in v0.220.0
type RestResource[Entity, ID any] struct { // Create will create a new entity in the restful resource. // POST / Create func(ctx context.Context, ptr *Entity) error // Index will return the entities, optionally filtered with the query argument. // GET / Index func(ctx context.Context, query url.Values) (iterators.Iterator[Entity], error) // Show will return a single entity, looked up by its ID. // GET /:id Show func(ctx context.Context, id ID) (ent Entity, found bool, err error) // Update will update/replace an entity with the new state. // PUT /:id - update/replace // PATCH /:id - partial update (WIP) Update func(ctx context.Context, id ID, ptr *Entity) error // Destroy will delete an entity, identified by its id. // Delete /:id Destroy func(ctx context.Context, id ID) error // DestroyAll will delete all entity. // Delete / DestroyAll func(ctx context.Context, query url.Values) error // Serialization is responsible to serialize and unserialize dtokit. // JSON, line separated JSON stream and FormUrlencoded formats are supported out of the box. // // Serialization is an optional field. // Unless you have specific needs in serialization, don't configure it. Serialization RestResourceSerialization[Entity, ID] // Mapping is the primary Entity to DTO mapping configuration. Mapping Mapping[Entity] // MappingForMIME defines a per MIMEType Mapping, that takes priority over Mapping MappingForMIME map[string]Mapping[Entity] // ErrorHandler is used to handle errors from the request, by mapping the error value into an error DTOMapping. ErrorHandler ErrorHandler // IDContextKey is an optional field used to store the parsed ID from the URL in the context. // // Default: IDContextKey[Entity, ID]{} IDContextKey any // SubRoutes is an http.Handler that will receive resource-specific requests. // SubRoutes is optional. // // The http.Request.Context will contain the parsed ID from the request path, // and can be accessed with the IDContextKey. // // Example paths // /plural-resource-identifier-name/:id/sub-routes // /users/42/status // /users/42/jobs/13 // // Request paths will be stripped from their prefix. // For example, "/users/42/jobs" will end up as "/jobs". SubRoutes http.Handler // BodyReadLimit is the max bytes that the handler is willing to read from the request body. // // The default value is DefaultBodyReadLimit, which is preset to 16MB. BodyReadLimit iokit.ByteSize }
RestResource is an HTTP Handler that allows you to expose a resource such as a repository as a Restful API resource. Depending on what CRUD operation is supported by the Handler.RestResource, the Handler supports the following actions:
Example ¶
fooRepository := memory.NewRepository[X, XID](memory.NewMemory()) fooRestfulResource := httpkit.RestResource[X, XID]{ Create: fooRepository.Create, Index: func(ctx context.Context, query url.Values) (iterators.Iterator[X], error) { foos := fooRepository.FindAll(ctx) if bt := query.Get("bigger"); bt != "" { bigger, err := strconv.Atoi(bt) if err != nil { return nil, err } foos = iterators.Filter(foos, func(foo X) bool { return bigger < foo.N }) } return foos, nil }, Show: fooRepository.FindByID, Update: func(ctx context.Context, id XID, ptr *X) error { ptr.ID = id return fooRepository.Update(ctx, ptr) }, Destroy: fooRepository.DeleteByID, Mapping: httpkit.DTOMapping[X, XDTO]{}, MappingForMIME: map[string]httpkit.Mapping[X]{ mediatype.JSON: httpkit.DTOMapping[X, XDTO]{}, }, } mux := http.NewServeMux() httpkit.Mount(mux, "/foos", fooRestfulResource)
func (RestResource[Entity, ID]) HTTPRequest ¶ added in v0.220.0
func (RestResource[Entity, ID]) ServeHTTP ¶ added in v0.220.0
func (res RestResource[Entity, ID]) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (RestResource[Entity, ID]) WithCRUD ¶ added in v0.220.0
func (res RestResource[Entity, ID]) WithCRUD(repo crud.ByIDFinder[Entity, ID]) RestResource[Entity, ID]
type RestResourceSerialization ¶ added in v0.220.0
type RestResourceSerialization[Entity, ID any] struct { Serializers map[string]Serializer IDConverter idConverter[ID] }
type RetryRoundTripper ¶
type RetryRoundTripper struct { // Transport specifies the mechanism by which individual // HTTP requests are made. // // Default: http.DefaultTransport Transport http.RoundTripper // RetryStrategy will be used to evaluate if a new retry attempt should be done. // // Default: retry.ExponentialBackoff RetryStrategy retry.Strategy[retry.FailureCount] // OnStatus is an [OPTIONAL] configuration field that could contain whether a certain http status code should be retried or not. // The RetryRoundTripper has a default behaviour about which status code can be retried, and this option can override that. OnStatus map[int]bool }
Example ¶
package main import ( "net/http" "time" "go.llib.dev/frameless/pkg/httpkit" "go.llib.dev/frameless/pkg/retry" ) func main() { httpClient := http.Client{ Transport: httpkit.RetryRoundTripper{ RetryStrategy: retry.ExponentialBackoff{ // optional Timeout: 5 * time.Minute, }, Transport: http.DefaultTransport, // optional OnStatus: map[int]bool{ // optional http.StatusTeapot: true, http.StatusTooManyRequests: false, }, }, } httpClient.Get("https://go.llib.dev") }
type RoundTripperFactoryFunc ¶ added in v0.216.0
type RoundTripperFactoryFunc func(next http.RoundTripper) http.RoundTripper
RoundTripperFactoryFunc is a constructor function that is meant to wrap an http.RoundTripper with given middleware. Its http.RoundTripper argument represents the next middleware http.RoundTripper in the pipeline.
type RoundTripperFunc ¶
type Router ¶ added in v0.220.0
type Router struct {
// contains filtered or unexported fields
}
Example ¶
var router httpkit.Router router.Namespace("/path", func(r *httpkit.Router) { r.Use(SampleMiddleware) r.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })) r.Post("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })) r.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // sub route catch-all handle })) r.Resource("foo", httpkit.RestResource[Foo, FooID]{ Mapping: httpkit.DTOMapping[Foo, FooDTO]{}, Index: func(ctx context.Context, query url.Values) (iterators.Iterator[Foo], error) { foo := Foo{ ID: "42", Foo: "foo", Bar: "bar", Baz: "baz", } return iterators.Slice([]Foo{foo}), nil }, }) }) router.Handle("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // handler that catches all requests that doesn't match anything directly })) router.Handle("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { // /foo endpoint for all methods }))
func (*Router) Connect ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Connect("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Delete ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Delete("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Get ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Get("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Handle ¶ added in v0.220.0
Handle registers the handler for the given pattern. If a handler already exists for pattern, Handle panics.
Example ¶
var router httpkit.Router var handler http.Handler // single endpoint router.Handle("/foo", handler) // catch all endpoint router.Handle("/foo/", handler)
func (*Router) Head ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Head("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Mount ¶ added in v0.220.0
Mount will mount a handler to the router. Mounting a handler will make the path observed as its root point to the handler. TODO: make this true :D
func (*Router) Namespace ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Namespace("/top", func(r *httpkit.Router) { r.Get("/sub", /* /top/sub */ http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) })) })
func (*Router) Patch ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Patch("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Post ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Post("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Put ¶ added in v0.220.0
Example ¶
var router httpkit.Router router.Put("/foo", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusTeapot) }))
func (*Router) Resource ¶ added in v0.220.0
Resource will register a restful resource path using the Resource handler.
Paths for Router.Resource("/users", restapi.Resource[User, UserID]):
GET /users POST /users GET /users/:id PUT /users/:id DELETE /users/:id
func (*Router) ServeHTTP ¶ added in v0.220.0
func (router *Router) ServeHTTP(w http.ResponseWriter, r *http.Request)
func (*Router) Use ¶ added in v0.220.0
func (router *Router) Use(mws ...MiddlewareFactoryFunc)
Use will instruct the router to use a given MiddlewareFactoryFunc to
type Serializer ¶ added in v0.220.0
type Serializer interface { serializers.Serializer }
type SerializerDefault ¶ added in v0.220.0
type SerializerDefault struct { Serializer interface { serializers.Serializer serializers.ListDecoderMaker } MIMEType string }