middleware

package
v0.4.1 Latest Latest
Warning

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

Go to latest
Published: May 20, 2022 License: MIT Imports: 9 Imported by: 0

Documentation

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func CorrelationId

func CorrelationId(options ...correlation_id.Option) httpware.Middleware

CorrelationId is a decoration of CorrelationId(github.com/gol4ng/httpware/v2/middleware) it will add correlationId to gol4ng/logger context this middleware require request context with a WrappableLoggerInterface in order to properly add correlationID to the logger context eg:

stack := httpware.MiddlewareStack(
	middleware.InjectLogger(l), // << Inject logger before CorrelationId
	middleware.CorrelationId(),
)
Example
port := ":5001"

myLogger := logger.NewLogger(
	handler.Stream(os.Stdout, formatter.NewDefaultFormatter(formatter.WithContext(true))),
)

// we recommend to use MiddlewareStack to simplify managing all wanted middlewares
// caution middleware order matters
stack := httpware.MiddlewareStack(
	http_middleware.InjectLogger(myLogger),
	http_middleware.CorrelationId(
		correlation_id.WithHeaderName("my-personal-header-name"),
		correlation_id.WithIdGenerator(func(request *http.Request) string {
			return "my-fixed-request-id"
		}),
	),
)

h := http.HandlerFunc(func(writer http.ResponseWriter, innerRequest *http.Request) {
	l := logger.FromContext(innerRequest.Context(), myLogger)
	l.Info("handler log info")
})

go func() {
	if err := http.ListenAndServe(port, stack.DecorateHandler(h)); err != nil {
		panic(err)
	}
}()

resp, err := http.Get("http://localhost" + port)
fmt.Printf("%s: %v %v\n", "my-personal-header-name", resp.Header.Get("my-personal-header-name"), err)
Output:

<info> handler log info {"my-personal-header-name":"my-fixed-request-id"}
my-personal-header-name: my-fixed-request-id <nil>

func InjectLogger

func InjectLogger(log logger.LoggerInterface) httpware.Middleware

InjectLogger will inject logger on request context if not exist this injection is made for every incoming request so prefer to use http.Server in order to create base context eg:

server := &http.Server{
	BaseContext: func(listener net.Listener) context.Context {
		return logger.InjectInContext(context.Background(), l)
	},
	...
}

func Logger

func Logger(log logger.LoggerInterface, opts ...logger_http.Option) httpware.Middleware

Logger will decorate the http.Handler to add support of gol4ng/logger

Types

This section is empty.

Jump to

Keyboard shortcuts

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