nethttp

package
v0.2.20 Latest Latest
Warning

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

Go to latest
Published: Feb 7, 2022 License: MIT Imports: 11 Imported by: 19

Documentation

Overview

Package nethttp provides instrumentation for net/http.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func AnnotateOpenAPI added in v0.1.5

func AnnotateOpenAPI(
	s *openapi.Collector,
	setup ...func(op *openapi3.Operation) error,
) func(http.Handler) http.Handler

AnnotateOpenAPI applies OpenAPI annotation to relevant handlers.

func AnnotateOperation

func AnnotateOperation(annotations ...func(operation *openapi3.Operation) error) func(h *Handler)

AnnotateOperation allows customizations of prepared operations.

func HTTPBasicSecurityMiddleware

func HTTPBasicSecurityMiddleware(
	c *openapi.Collector,
	name, description string,
	options ...func(*MiddlewareConfig),
) func(http.Handler) http.Handler

HTTPBasicSecurityMiddleware creates middleware to expose 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

func HandlerAs(handler http.Handler, target interface{}) bool

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

func HandlerWithRouteMiddleware(method, pathPattern string) func(http.Handler) http.Handler

HandlerWithRouteMiddleware wraps handler with routing information.

func OpenAPIMiddleware

func OpenAPIMiddleware(s *openapi.Collector) func(http.Handler) http.Handler

OpenAPIMiddleware reads info and adds validation to handler.

func OptionsMiddleware added in v0.1.21

func OptionsMiddleware(options ...func(h *Handler)) func(h http.Handler) http.Handler

OptionsMiddleware applies options to encountered nethttp.Handler.

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

Example
// Create router.
r := chirouter.NewWrapper(chi.NewRouter())

// Init API documentation schema.
apiSchema := &openapi.Collector{}

// Setup middlewares (non-documentary middlewares omitted for brevity).
r.Use(
	nethttp.OpenAPIMiddleware(apiSchema), // Documentation collector.
)

// 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.SecurityMiddleware(apiSchema, "serviceToken", openapi3.SecurityScheme{
	APIKeySecurityScheme: &openapi3.APIKeySecurityScheme{
		Name: "Authorization",
		In:   openapi3.APIKeySecuritySchemeInHeader,
	},
})

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.
r.
	With(serviceTokenAuth, serviceTokenDoc). // Apply a pair of middlewares: actual security and documentation.
	Method(http.MethodGet, "/foo", nethttp.NewHandler(u))
Output:

func SecurityResponse added in v0.1.20

func SecurityResponse(structure interface{}, httpStatus int) func(config *MiddlewareConfig)

SecurityResponse is an security middleware option to customize response structure and status.

func SuccessStatus

func SuccessStatus(status int) func(h *Handler)

SuccessStatus sets status code of successful response.

func SuccessfulResponseContentType

func SuccessfulResponseContentType(contentType string) func(h *Handler)

SuccessfulResponseContentType sets Content-Type of successful response.

func UseCaseMiddlewares

func UseCaseMiddlewares(mw ...usecase.Middleware) func(http.Handler) http.Handler

UseCaseMiddlewares applies use case middlewares to Handler.

func WrapHandler

func WrapHandler(h http.Handler, mw ...func(http.Handler) http.Handler) http.Handler

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

Jump to

Keyboard shortcuts

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