Documentation
¶
Overview ¶
Package nethttp provides instrumentation for net/http.
Index ¶
- func APIKeySecurityMiddleware(c *openapi.Collector, name string, fieldName string, fieldIn oapi.In, ...) func(http.Handler) http.Handler
- func AnnotateOpenAPI(s *openapi.Collector, setup ...func(op *openapi3.Operation) error) func(http.Handler) http.Handlerdeprecated
- func AnnotateOpenAPIOperation(annotations ...func(oc openapi.OperationContext) error) func(h *Handler)
- func AnnotateOperation(annotations ...func(operation *openapi3.Operation) error) func(h *Handler)deprecated
- func AuthMiddleware(c *openapi.Collector, name string, options ...func(*MiddlewareConfig)) func(http.Handler) http.Handler
- func CollectRouteOperation(coll *openapi.Collector, method, path string, preparer RoutePreparerFunc) error
- func Describe(h http.HandlerFunc, setup RoutePreparerFunc) http.Handler
- func HTTPBasicSecurityMiddleware(c *openapi.Collector, name, description string, ...) func(http.Handler) http.Handler
- func HTTPBearerSecurityMiddleware(c *openapi.Collector, name, description, bearerFormat string, ...) func(http.Handler) http.Handler
- func HandlerAs(handler http.Handler, target interface{}) bool
- func HandlerWithRouteMiddleware(method, pathPattern string) func(http.Handler) http.Handler
- func IsWrapperChecker(h http.Handler) bool
- func MiddlewareIsWrapper(mw func(h http.Handler) http.Handler) bool
- func OpenAPIAnnotationsMiddleware(s *openapi.Collector, annotations ...func(oc oapi.OperationContext) error) func(http.Handler) http.Handler
- func OpenAPIMiddleware(s *openapi.Collector) func(http.Handler) http.Handler
- func OptionsMiddleware(options ...func(h *Handler)) func(h http.Handler) http.Handler
- func RequestBodyContent(contentType string) func(h *Handler)
- func RequestMapping(v interface{}) func(h *Handler)
- func ResponseHeaderMapping(v interface{}) func(h *Handler)
- func SecurityMiddleware(c *openapi.Collector, name string, scheme openapi3.SecurityScheme, ...) func(http.Handler) http.Handlerdeprecated
- func SecurityResponse(structure interface{}, httpStatus int) func(config *MiddlewareConfig)
- func SuccessStatus(status int) func(h *Handler)
- func SuccessfulResponseContentType(contentType string) func(h *Handler)
- func UseCaseMiddlewares(mw ...usecase.Middleware) func(http.Handler) http.Handler
- func WrapHandler(h http.Handler, mw ...func(http.Handler) http.Handler) http.Handler
- type Handler
- func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
- func (h *Handler) SetRequestDecoder(requestDecoder RequestDecoder)
- func (h *Handler) SetResponseEncoder(responseEncoder ResponseEncoder)
- func (h *Handler) SetUseCase(useCase usecase.Interactor)
- func (h *Handler) UseCase() usecase.Interactor
- type MiddlewareConfig
- type RequestDecoder
- type ResponseEncoder
- type RoutePreparer
- type RoutePreparerFunc
Examples ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func APIKeySecurityMiddleware ¶ added in v0.2.55
func APIKeySecurityMiddleware( c *openapi.Collector, name string, fieldName string, fieldIn oapi.In, description string, options ...func(*MiddlewareConfig), ) func(http.Handler) http.Handler
APIKeySecurityMiddleware creates middleware to expose API Key security schema.
func AnnotateOpenAPIOperation ¶ added in v0.2.54
func AnnotateOpenAPIOperation(annotations ...func(oc openapi.OperationContext) error) func(h *Handler)
AnnotateOpenAPIOperation allows customization of OpenAPI operation, that is reflected from the Handler.
func AnnotateOperation
deprecated
func AuthMiddleware ¶ added in v0.2.55
func AuthMiddleware( c *openapi.Collector, name string, options ...func(*MiddlewareConfig), ) func(http.Handler) http.Handler
AuthMiddleware creates middleware to expose security scheme.
func CollectRouteOperation ¶ added in v0.2.76
func CollectRouteOperation(coll *openapi.Collector, method, path string, preparer RoutePreparerFunc) error
CollectRouteOperation prepares and adds an OpenAPI operation, falling back to a best-effort "Incomplete" description (derived from method/path alone) when there is no preparer and no prior annotation.
func Describe ¶ added in v0.2.76
func Describe(h http.HandlerFunc, setup RoutePreparerFunc) http.Handler
Describe attaches OpenAPI documentation to a http.HandlerFunc. Unlike Collector.AnnotateOperation, which is keyed by a separately maintained method+pattern string that can drift from the actual route, Describe keeps the route registration itself as the single source of truth: it wraps the handler so Preparer recognizes it the same way as a handler that implements RoutePreparer directly.
The result implements http.Handler, so register it with a method that accepts one (e.g. chi's Method/Handle, or gorilla/mux's Handle), not one that requires http.HandlerFunc.
func HTTPBasicSecurityMiddleware ¶
func HTTPBasicSecurityMiddleware( c *openapi.Collector, name, description string, options ...func(*MiddlewareConfig), ) func(http.Handler) http.Handler
HTTPBasicSecurityMiddleware creates middleware to expose HTTP Basic security schema.
func HTTPBearerSecurityMiddleware ¶
func HTTPBearerSecurityMiddleware( c *openapi.Collector, name, description, bearerFormat string, options ...func(*MiddlewareConfig), ) func(http.Handler) http.Handler
HTTPBearerSecurityMiddleware creates middleware to expose HTTP Bearer security schema.
func HandlerAs ¶
HandlerAs finds the first http.Handler in http.Handler's chain that matches target, and if so, sets target to that http.Handler value and returns true.
An http.Handler matches target if the http.Handler's concrete value is assignable to the value pointed to by target.
HandlerAs will panic if target is not a non-nil pointer to either a type that implements http.Handler, or to any interface type.
func HandlerWithRouteMiddleware ¶
HandlerWithRouteMiddleware wraps handler with routing information.
func IsWrapperChecker ¶ added in v0.2.34
IsWrapperChecker is a hack to mark middleware as a handler wrapper. See chirouter.Wrapper Wrap() documentation for more details on the difference.
Wrappers should invoke the check and do early return if it succeeds.
func MiddlewareIsWrapper ¶ added in v0.2.34
MiddlewareIsWrapper is a hack to detect whether middleware is a handler wrapper. See chirouter.Wrapper Wrap() documentation for more details on the difference.
func OpenAPIAnnotationsMiddleware ¶ added in v0.2.54
func OpenAPIAnnotationsMiddleware( s *openapi.Collector, annotations ...func(oc oapi.OperationContext) error, ) func(http.Handler) http.Handler
OpenAPIAnnotationsMiddleware applies OpenAPI annotations to handlers.
func OpenAPIMiddleware ¶
OpenAPIMiddleware reads info and adds validation to handler.
func OptionsMiddleware ¶ added in v0.1.21
OptionsMiddleware applies options to encountered nethttp.Handler.
func RequestBodyContent ¶ added in v0.2.41
RequestBodyContent enables string request body with content type (e.g. text/plain).
func RequestMapping ¶
func RequestMapping(v interface{}) func(h *Handler)
RequestMapping creates rest.RequestMapping from struct tags.
This can be used to decouple mapping from usecase input with additional struct.
func ResponseHeaderMapping ¶
func ResponseHeaderMapping(v interface{}) func(h *Handler)
ResponseHeaderMapping creates headers mapping from struct tags.
This can be used to decouple mapping from usecase input with additional struct.
func SecurityMiddleware
deprecated
added in
v0.1.22
func SecurityMiddleware( c *openapi.Collector, name string, scheme openapi3.SecurityScheme, options ...func(*MiddlewareConfig), ) func(http.Handler) http.Handler
SecurityMiddleware creates middleware to expose security scheme.
Deprecated: use AuthMiddleware.
Example ¶
package main
import (
"context"
"fmt"
"net/http"
"github.com/swaggest/assertjson"
oapi "github.com/swaggest/openapi-go"
"github.com/swaggest/openapi-go/openapi3"
"github.com/swaggest/rest/nethttp"
"github.com/swaggest/rest/web"
"github.com/swaggest/usecase"
)
func main() {
// Create router.
s := web.NewService(openapi3.NewReflector())
// Configure an actual security middleware.
serviceTokenAuth := func(h http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
if req.Header.Get("Authorization") != "<secret>" {
http.Error(w, "Authentication failed.", http.StatusUnauthorized)
return
}
h.ServeHTTP(w, req)
})
}
// Configure documentation middleware to describe actual security middleware.
serviceTokenDoc := nethttp.APIKeySecurityMiddleware(s.OpenAPICollector,
"serviceToken", "Authorization", oapi.InHeader, "Service token.")
u := usecase.NewIOI(nil, nil, func(ctx context.Context, input, output interface{}) error {
// Do something.
return nil
})
// Add use case handler to router with security middleware.
s.
With(serviceTokenAuth, serviceTokenDoc). // Apply a pair of middlewares: actual security and documentation.
Method(http.MethodGet, "/foo", nethttp.NewHandler(u))
schema, _ := assertjson.MarshalIndentCompact(s.OpenAPISchema(), "", " ", 120)
fmt.Println(string(schema))
}
Output: { "openapi":"3.0.3","info":{"title":"","version":""}, "paths":{ "/foo":{ "get":{ "summary":"Example Security Middleware","operationId":"rest/nethttp_test.ExampleSecurityMiddleware", "responses":{ "204":{"description":"No Content"}, "401":{ "description":"Unauthorized", "content":{"application/json":{"schema":{"$ref":"#/components/schemas/RestErrResponse"}}} } }, "security":[{"serviceToken":[]}] } } }, "components":{ "schemas":{ "RestErrResponse":{ "type":"object", "properties":{ "code":{"type":"integer","description":"Application-specific error code."}, "context":{"type":"object","additionalProperties":{},"description":"Application context."}, "error":{"type":"string","description":"Error message."},"status":{"type":"string","description":"Status text."} } } }, "securitySchemes":{"serviceToken":{"type":"apiKey","name":"Authorization","in":"header","description":"Service token."}} } }
func SecurityResponse ¶ added in v0.1.20
func SecurityResponse(structure interface{}, httpStatus int) func(config *MiddlewareConfig)
SecurityResponse is a security middleware option to customize response structure and status.
func SuccessStatus ¶
SuccessStatus sets status code of successful response.
func SuccessfulResponseContentType ¶
SuccessfulResponseContentType sets Content-Type of successful response.
func UseCaseMiddlewares ¶
UseCaseMiddlewares applies use case middlewares to Handler.
func WrapHandler ¶
WrapHandler wraps http.Handler with an unwrappable middleware.
Wrapping order is reversed, e.g. if you call WrapHandler(h, mw1, mw2, mw3) middlewares will be invoked in order of mw1(mw2(mw3(h))), mw3 first and mw1 last. So that request processing is first affected by mw1.
Types ¶
type Handler ¶
type Handler struct {
rest.HandlerTrait
// HandleErrResponse allows control of error response processing.
HandleErrResponse func(w http.ResponseWriter, r *http.Request, err error)
// contains filtered or unexported fields
}
Handler is a use case http handler with documentation and inputPort validation.
Please use NewHandler to create instance.
func NewHandler ¶
func NewHandler(useCase usecase.Interactor, options ...func(h *Handler)) *Handler
NewHandler creates use case http handler.
func (*Handler) ServeHTTP ¶
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request)
ServeHTTP serves http inputPort with use case interactor.
func (*Handler) SetRequestDecoder ¶
func (h *Handler) SetRequestDecoder(requestDecoder RequestDecoder)
SetRequestDecoder sets request decoder.
func (*Handler) SetResponseEncoder ¶
func (h *Handler) SetResponseEncoder(responseEncoder ResponseEncoder)
SetResponseEncoder sets response encoder.
func (*Handler) SetUseCase ¶
func (h *Handler) SetUseCase(useCase usecase.Interactor)
SetUseCase prepares handler for a use case.
func (*Handler) UseCase ¶
func (h *Handler) UseCase() usecase.Interactor
UseCase returns use case interactor.
type MiddlewareConfig ¶ added in v0.1.20
type MiddlewareConfig struct {
// ResponseStructure declares structure that is used for unauthorized message, default rest.ErrResponse{}.
ResponseStructure interface{}
// ResponseStatus declares HTTP status code that is used for unauthorized message, default http.StatusUnauthorized.
ResponseStatus int
}
MiddlewareConfig defines security middleware options.
type RequestDecoder ¶
type RequestDecoder interface {
// Decode fills input with data from request, input should be a pointer.
Decode(r *http.Request, input interface{}, validator rest.Validator) error
}
RequestDecoder maps data from http.Request into structured Go input value.
type ResponseEncoder ¶
type ResponseEncoder interface {
WriteErrResponse(w http.ResponseWriter, r *http.Request, statusCode int, response interface{})
WriteSuccessfulResponse(
w http.ResponseWriter,
r *http.Request,
output interface{},
ht rest.HandlerTrait,
)
SetupOutput(output interface{}, ht *rest.HandlerTrait)
MakeOutput(w http.ResponseWriter, ht rest.HandlerTrait) interface{}
}
ResponseEncoder writes data from use case output/error into http.ResponseWriter.
type RoutePreparer ¶ added in v0.2.76
type RoutePreparer interface {
SetupOpenAPIOperation(oc oapi.OperationContext) error
}
RoutePreparer defines http.Handler with OpenAPI information.
It is used by router adapters (such as chirouter and gorillamux) that augment an existing http.Handler-based router instead of wrapping typed usecase interactors. Third-party router adapters can implement the same collection flow with Describe, Preparer and CollectRouteOperation.
type RoutePreparerFunc ¶ added in v0.2.76
type RoutePreparerFunc func(oc oapi.OperationContext) error
RoutePreparerFunc sets up OpenAPI operation.
func Preparer ¶ added in v0.2.76
func Preparer( handler http.Handler, extractor func(h http.Handler) func(oc oapi.OperationContext) error, ) RoutePreparerFunc
Preparer resolves the preparer func for handler: interface implementation first (this is also how a handler wrapped with Describe is recognized), then the extractor as a last resort.