middleware

package module
v0.4.3 Latest Latest
Warning

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

Go to latest
Published: Nov 24, 2020 License: MIT Imports: 13 Imported by: 14

README

middleware

net/http middleware collection

Middleware

type Middleware func(h http.Handler) http.Handler
Create new middleware
func say(text string) Middleware {
    return func(h http.Handler) http.Handler {
        return http.HandlerFunc(func (w http.ResponseWriter, r *http.Request) {
            fmt.Println(text)
            h.ServeHTTP(w, r)
        })
    }
}

Chaining

Like normal function middleware can chained.

middleware.HSTSPreload()(middleware.NonWWWRedirect()(say("hello")(handler)))

Or using Chain to create new middleware

newMiddleware := middleware.Chain(
    middleware.HSTSPreload(),
    middleware.NonWWWRedirect(),
    say("hello"),
)

Then

handler = newMiddleware(handler)

HSTS

middleware.HSTS(HSTSConfig{
    MaxAge:            3600 * time.Second,
    IncludeSubDomains: true,
    Preload:           false,
})
middleware.HSTS(middleware.DefaultHSTS)
middleware.HSTS(middleware.PreloadHSTS)
middleware.HSTSPreload()

Compressor

middleware.Compress(middleware.CompressConfig{
    New: func() Compressor {
        g, err := gzip.NewWriterLevel(ioutil.Discard, gzip.DefaultCompression)
        if err != nil {
            panic(err)
        }
        return g
    },
    Encoding:  "gzip",
    Vary:      true,
    Types:     "text/plain text/html",
    MinLength: 1000,
})
middleware.Compress(middleware.GzipCompressor)
middleware.Compress(middleware.DeflateCompressor)
BrCompressor
middleware.Compress(middleware.BrCompressor)
FROM alpine

RUN apk add --no-cache ca-certificates tzdata

RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk --no-cache add brotli

RUN mkdir -p /app
WORKDIR /app

ADD entrypoint ./
ENTRYPOINT ["/app/entrypoint"]

or using acoshift/go-alpine

FROM acoshift/go-alpine

RUN echo "http://dl-cdn.alpinelinux.org/alpine/edge/testing" >> /etc/apk/repositories
RUN apk --no-cache add brotli

RUN mkdir -p /app
WORKDIR /app

ADD entrypoint ./
ENTRYPOINT ["/app/entrypoint"]

Builder

use acoshift/gobuilder or build your own build image

FROM gcr.io/cloud-builders/go

RUN apk --no-cache add cmake

RUN git clone https://github.com/google/brotli && cd brotli && cmake . && make install && cd .. && rm -rf brotli

and add -tags=cbrotli when using go build

Compress Order

Unlike normal middleware, compressor have to peek on response header. Order will reverse ex.

middleware.Chain(
    middleware.Compress(middleware.DeflateCompressor),
    middleware.Compress(middleware.GzipCompressor),
    middleware.Compress(middleware.BrCompressor),
)

Code above will run br first, if client not support br, the gzip compressor will be run. Then if client not support both br and gzip, the deflate compressor will be run.

Redirector

Redirect from www to non-www
middleware.NonWWWRedirect()
Redirect from non-www to www
middleware.WWWRedirect()
Redirect from http to https

TODO

CORS

middleware.CORS(middleware.DefaultCORS) // for public api
middleware.CORS(CORSConfig{
    AllowOrigins: []string{"example.com"},
    AllowMethods: []string{
        http.MethodGet,
        http.MethodPost,
    },
    AllowHeaders: []string{
        "Content-Type",
    },
    AllowCredentials: true,
    MaxAge: time.Hour,
})

CSRF

CSRF will reject origin or referal that not in whitelist on POST.

middleware.CSRF(middleware.CSRFConfig{
    Origins: []string{
        "http://example.com",
        "https://example.com",
        "http://www.example.com",
        "https://www.example.com",
    },
})

or using IgnoreProto to ignore protocol

middleware.CSRF(middleware.CSRFConfig{
    Origins: []string{
        "example.com",
        "www.example.com",
    },
    IgnoreProto: true,
})

Ratelimit

TODO

Logging

TODO

Add Header

AddHeader is a helper middleware to add a header to response writer if not exists

middleware.AddHeader("Vary", "Origin")

License

MIT

Documentation

Index

Constants

This section is empty.

Variables

View Source
var (
	GzipCompressor = CompressConfig{
		Skipper: DefaultSkipper,
		New: func() Compressor {
			g, err := gzip.NewWriterLevel(ioutil.Discard, gzip.DefaultCompression)
			if err != nil {
				panic(err)
			}
			return g
		},
		Encoding:  "gzip",
		Vary:      defaultCompressVary,
		Types:     defaultCompressTypes,
		MinLength: defaultCompressMinLength,
	}

	DeflateCompressor = CompressConfig{
		Skipper: DefaultSkipper,
		New: func() Compressor {
			g, err := flate.NewWriter(ioutil.Discard, flate.DefaultCompression)
			if err != nil {
				panic(err)
			}
			return g
		},
		Encoding:  "deflate",
		Vary:      defaultCompressVary,
		Types:     defaultCompressTypes,
		MinLength: defaultCompressMinLength,
	}
)

pre-defined compressors

View Source
var (
	DefaultHSTS = HSTSConfig{
		Skipper:           SkipHTTP,
		MaxAge:            31536000 * time.Second,
		IncludeSubDomains: false,
		Preload:           false,
	}

	PreloadHSTS = HSTSConfig{
		Skipper:           SkipHTTP,
		MaxAge:            63072000 * time.Second,
		IncludeSubDomains: true,
		Preload:           true,
	}
)

Pre-defiend config

View Source
var BrCompressor = CompressConfig{
	Skipper: AlwaysSkip,
}

BrCompressor is a noop compressor fallback for br

View Source
var DefaultCORS = CORSConfig{
	AllowAllOrigins: true,
	AllowMethods: []string{
		http.MethodGet,
		http.MethodPost,
		http.MethodPut,
		http.MethodPatch,
		http.MethodDelete,
	},
	AllowHeaders: []string{
		"Content-Type",
		"Authorization",
	},
	MaxAge: time.Hour,
}

DefaultCORS is the default cors config for public api

Functions

func AlwaysSkip added in v0.4.0

func AlwaysSkip(*http.Request) bool

AlwaysSkip always return true

func CSRF added in v0.4.0

func CSRF(c CSRFConfig) func(http.Handler) http.Handler

CSRF creates new csrf middleware

func DefaultSkipper

func DefaultSkipper(*http.Request) bool

DefaultSkipper always return false

func SkipHTTP added in v0.2.0

func SkipHTTP(r *http.Request) bool

SkipHTTP skips http request

func SkipHTTPS added in v0.2.0

func SkipHTTPS(r *http.Request) bool

SkipHTTPS skips https request

Types

type CORSConfig added in v0.4.0

type CORSConfig struct {
	Skipper          Skipper
	AllowAllOrigins  bool
	AllowOrigins     []string
	AllowMethods     []string
	AllowHeaders     []string
	AllowCredentials bool
	ExposeHeaders    []string
	MaxAge           time.Duration
}

CORSConfig is the cors config

type CSRFConfig added in v0.4.0

type CSRFConfig struct {
	Origins          []string
	ForbiddenHandler http.Handler
	IgnoreProto      bool
	Force            bool
}

CSRFConfig is the csrf config

type CompressConfig added in v0.3.0

type CompressConfig struct {
	Skipper   Skipper
	New       func() Compressor
	Encoding  string // http Accept-Encoding, Content-Encoding value
	Vary      bool   // add Vary: Accept-Encoding
	Types     string // only compress for given types, * for all types
	MinLength int    // skip if Content-Length less than given value
}

CompressConfig is the compress middleware config

type Compressor added in v0.3.0

type Compressor interface {
	io.Writer
	io.Closer
	Reset(io.Writer)
	Flush() error
}

Compressor type

type HSTSConfig added in v0.3.0

type HSTSConfig struct {
	Skipper           Skipper
	MaxAge            time.Duration
	IncludeSubDomains bool
	Preload           bool
}

HSTSConfig is the HSTS config

type Middleware

type Middleware func(http.Handler) http.Handler

Middleware is the http middleware

func AddHeader added in v0.4.0

func AddHeader(key, value string) Middleware

AddHeader creates new middleware that adds a header to response

func CORS added in v0.4.0

func CORS(config CORSConfig) Middleware

CORS creates new CORS middleware

func Chain

func Chain(hs ...Middleware) Middleware

Chain is the helper function for chain middlewares into one middleware

func Compress added in v0.3.0

func Compress(config CompressConfig) Middleware

Compress creates new compress middleware

func HSTS added in v0.3.0

func HSTS(config HSTSConfig) Middleware

HSTS creates new HSTS middleware

func HSTSPreload added in v0.3.0

func HSTSPreload() Middleware

HSTSPreload is the short-hand for HSTS(PreloadHSTS)

func NonWWWRedirect

func NonWWWRedirect() Middleware

NonWWWRedirect redirects www to non-www

func WWWRedirect added in v0.3.0

func WWWRedirect() Middleware

WWWRedirect redirects non-www to www

type Skipper

type Skipper func(*http.Request) bool

Skipper is the function to skip middleware, return true will skip middleware

func SkipIf added in v0.3.0

func SkipIf(b bool) Skipper

SkipIf skips if b is true

func SkipUnless added in v0.3.0

func SkipUnless(b bool) Skipper

SkipUnless skips if b is false

Jump to

Keyboard shortcuts

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