middleware

package
v3.14.0 Latest Latest
Warning

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

Go to latest
Published: Mar 28, 2021 License: Apache-2.0 Imports: 15 Imported by: 0

Documentation

Overview

Package middleware is the collection of the middlewares.

Index

Constants

This section is empty.

Variables

View Source
var (
	ErrTokenFromHeader = errors.New("missing token in the url header")
	ErrTokenFromQuery  = errors.New("missing token in the url query")
	ErrTokenFromForm   = errors.New("missing token in the form parameter")
)

Predefine some errors.

Functions

func GenerateToken

func GenerateToken(n int, charsets ...string) func() string

GenerateToken returns a token generator which will generate a n-length token string.

func IsNoTokenError

func IsNoTokenError(err error) bool

IsNoTokenError reports whether the error is that there is no token.

Types

type CORSConfig

type CORSConfig struct {
	// AllowOrigin defines a list of origins that may access the resource.
	//
	// Optional. Default: []string{"*"}.
	AllowOrigins []string

	// AllowHeaders indicates a list of request headers used in response to
	// a preflight request to indicate which HTTP headers can be used when
	// making the actual request. This is in response to a preflight request.
	//
	// Optional. Default: []string{}.
	AllowHeaders []string

	// AllowMethods indicates methods allowed when accessing the resource.
	// This is used in response to a preflight request.
	//
	// Optional. Default: []string{"HEAD", "GET", "POST", "PUT", "PATHC", "DELETE"}.
	AllowMethods []string

	// ExposeHeaders indicates a server whitelist headers that browsers are
	// allowed to access. This is in response to a preflight request.
	//
	// Optional. Default: []string{}.
	ExposeHeaders []string

	// AllowCredentials indicates whether or not the response to the request
	// can be exposed when the credentials flag is true. When used as part of
	// a response to a preflight request, this indicates whether or not the
	// actual request can be made using credentials.
	//
	// Optional. Default: false.
	AllowCredentials bool

	// MaxAge indicates how long (in seconds) the results of a preflight request
	// can be cached.
	//
	// Optional. Default: 0.
	MaxAge int
}

CORSConfig is used to configure the CORS middleware.

type CSRFConfig

type CSRFConfig struct {
	CookieCtxKey   string
	CookieName     string
	CookiePath     string
	CookieDomain   string
	CookieMaxAge   int
	CookieSecure   bool
	CookieHTTPOnly bool

	GenerateToken       func() string
	GetTokenFromRequest TokenFunc
}

CSRFConfig is used to configure the CSRF middleware.

type LoggerConfig added in v3.8.0

type LoggerConfig struct {
	// If true, log the request body.
	//
	// Default: false
	LogReqBody bool
}

LoggerConfig is used to configure the logger middleware.

type Middleware

type Middleware = ship.Middleware

Middleware is the alias of ship.Middleware.

We add it in order to show the middlewares in together by the godoc.

func BodyLimit

func BodyLimit(maxBodySize int64) Middleware

BodyLimit is used to limit the maximum body of the request.

func CORS

func CORS(config ...CORSConfig) Middleware

CORS returns a CORS middleware.

If the config is missing, it will use:

conf := CORSConfig{
    AllowOrigins: []string{"*"},
    AllowMethods: []string{"HEAD", "GET", "POST", "PUT", "PATHC", "DELETE"},
}

func CSRF

func CSRF(config ...CSRFConfig) Middleware

CSRF returns a CSRF middleware.

If the config is missing, it will use:

conf := CSRFConfig{
    CookieName:   "_csrf",
    CookieCtxKey: "csrf",
    CookieMaxAge: 86400,

    GenerateToken:       GenerateToken(32),
    GetTokenFromRequest: GetTokenFromHeader(ship.HeaderXCSRFToken),
}

func CleanPath

func CleanPath() Middleware

CleanPath returns a new middleware to clean the request path.

Notice: it should be used as the pre-middleware by ship#Pre().

func FromFunc

func FromFunc(f func(ctx *ship.Context, next ship.Handler) error) Middleware

FromFunc converts a function to a middleware.

func Gzip

func Gzip(level ...int) Middleware

Gzip returns a middleware to compress the response body by GZIP.

func Logger

func Logger(config ...LoggerConfig) Middleware

Logger returns a new logger middleware that will log the request.

func MaxRequests

func MaxRequests(max uint32, handler ...ship.Handler) Middleware

MaxRequests returns a Middleware to allow the maximum number of the requests to max at a time.

If the number of the requests exceeds the maximum, it will call the handler, which return the status code 429. But you can appoint yourself handler.

func Recover

func Recover() Middleware

Recover returns a middleware to wrap the panic.

func RemoveTrailingSlash

func RemoveTrailingSlash() Middleware

RemoveTrailingSlash returns a new middleware to remove the trailing slash in the request path if it exists.

Notice: it should be used as the pre-middleware by ship#Pre().

func ReqBodyLogger added in v3.4.0

func ReqBodyLogger() Middleware

ReqBodyLogger returns a middleware to log the request body.

DEPRECATED! Please use Logger instead.

func RequestID

func RequestID(generateRequestID ...func() string) Middleware

RequestID returns a X-Request-ID middleware.

If the request header does not contain X-Request-ID, it will set a new one.

generateRequestID is GenerateToken(32).

func TokenAuth

func TokenAuth(validator TokenValidator, getToken ...TokenFunc) Middleware

TokenAuth returns a TokenAuth middleware.

For valid key it will calls the next handler. For invalid key, it responds "401 Unauthorized". For missing key, it responds "400 Bad Request".

If getToken is missing, the default is GetTokenFromHeader(ship.HeaderAuthorization, "Bearer").

type TokenFunc

type TokenFunc func(ctx *ship.Context) (token string, err error)

TokenFunc stands for a function to get a token from the request context.

func GetTokenFromForm

func GetTokenFromForm(param string) TokenFunc

GetTokenFromForm is used to get the token from the request FORM body.

func GetTokenFromHeader

func GetTokenFromHeader(header string, _type ...string) TokenFunc

GetTokenFromHeader is used to get the token from the request header.

You can appoint the type of the token, which is separated by a whitespace, such as the header "Authorization".

func GetTokenFromQuery

func GetTokenFromQuery(param string) TokenFunc

GetTokenFromQuery is used to get the token from the request URL query.

type TokenValidator

type TokenValidator func(token string) (ok bool, err error)

TokenValidator stands for a validator to validate whether a token is valid.

Jump to

Keyboard shortcuts

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