Categorygithub.com/acoshift/middleware
modulepackage
0.4.3
Repository: https://github.com/acoshift/middleware.git
Documentation: pkg.go.dev

# 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

# Functions

AddHeader creates new middleware that adds a header to response.
AlwaysSkip always return true.
Chain is the helper function for chain middlewares into one middleware.
Compress creates new compress middleware.
CORS creates new CORS middleware.
CSRF creates new csrf middleware.
DefaultSkipper always return false.
HSTS creates new HSTS middleware.
HSTSPreload is the short-hand for HSTS(PreloadHSTS).
NonWWWRedirect redirects www to non-www.
SkipHTTP skips http request.
SkipHTTPS skips https request.
SkipIf skips if b is true.
SkipUnless skips if b is false.
WWWRedirect redirects non-www to www.

# Variables

BrCompressor is a noop compressor fallback for br.
DefaultCORS is the default cors config for public api.
Pre-defiend config.
pre-defined compressors.
pre-defined compressors.
Pre-defiend config.

# Structs

CompressConfig is the compress middleware config.
CORSConfig is the cors config.
CSRFConfig is the csrf config.
HSTSConfig is the HSTS config.

# Interfaces

Compressor type.

# Type aliases

Middleware is the http middleware.
Skipper is the function to skip middleware, return true will skip middleware.