finalizer

package module
v0.0.0-...-91592c9 Latest Latest
Warning

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

Go to latest
Published: Aug 6, 2021 License: MIT Imports: 3 Imported by: 0

README

GoDoc

Finalizer is a Go package that implements an HTTP Middleware with a callback that gets called at the end of every request. Typically used to implement HTTP logging.

The code in this package has been adapted from the Go-Kit http server code.

Documentation

Overview

Package finalizer implements an HTTP Middleware with a callback that's executed at the end of the HTTP request.

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func Header(ctx context.Context) (http.Header, bool)

Header returns the HTTP Response headers from a ServerFinalizerFunc context.

func Middleware

func Middleware(finalizer ServerFinalizerFunc, next http.Handler) http.Handler

Middleware calls the ServerFinalizerFunc at the end of an HTTP Request.

Example
//finalizer is executed at the end of the HTTP request in Middleware.
finalizer := func(ctx context.Context, code int, r *http.Request) {
	header, _ := Header(ctx)
	size, _ := ResponseSize(ctx)
	contentType := header.Get("Content-Type")

	fmt.Printf("status=%d, contentType=%s, responseSize=%d\n", code, contentType, size)
}

handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
	w.WriteHeader(http.StatusTeapot)
	w.Header().Set("Content-Type", "message/teapot")
	w.Write([]byte("I brew Tea"))
})

// wrap the handler with the finalizer middleware.
wrappedHandler := Middleware(finalizer, handler)

srv := httptest.NewServer(wrappedHandler)
defer srv.Close()

if _, err := http.Get(srv.URL); err != nil {
	panic(err)
}
Output:

status=418, contentType=message/teapot, responseSize=0

func ResponseSize

func ResponseSize(ctx context.Context) (int, bool)

ResponseSize returns the written response size from a ServerFinalizerFunc context.

Types

type ServerFinalizerFunc

type ServerFinalizerFunc func(ctx context.Context, code int, r *http.Request)

ServerFinalizerFunc is a function executed at the end of an HTTP request.

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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