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 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
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 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.