Documentation ¶
Overview ¶
Package middleware is the collection of the middlewares.
Index ¶
- Variables
- func GenerateToken(n int, charsets ...string) func() string
- func IsNoTokenError(err error) bool
- type CORSConfig
- type CSRFConfig
- type Middleware
- func BodyLimit(maxBodySize int64) Middleware
- func CORS(config ...CORSConfig) Middleware
- func CSRF(config ...CSRFConfig) Middleware
- func CleanPath() Middleware
- func Flat(befores, afters []ship.Handler) Middleware
- func FromFunc(f func(ctx *ship.Context, next ship.Handler) error) Middleware
- func Gzip(level ...int) Middleware
- func Logger(now ...func() time.Time) Middleware
- func Matchers(matchers []ship.Matcher, handleError ...func(*ship.Context, error) error) Middleware
- func MaxRequests(max uint32, handler ...ship.Handler) Middleware
- func Recover(handle ...func(*ship.Context, interface{})) Middleware
- func RemoveTrailingSlash() Middleware
- func RequestID(generateRequestID ...func() string) Middleware
- func ResetResponse(reset func(http.ResponseWriter) http.ResponseWriter) Middleware
- func SetCtxHandler(h func(*ship.Context, ...interface{}) error) Middleware
- func TokenAuth(validator TokenValidator, getToken ...TokenFunc) Middleware
- type TokenFunc
- type TokenValidator
Constants ¶
This section is empty.
Variables ¶
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 ¶
GenerateToken returns a token generator which will generate a n-length token string.
func IsNoTokenError ¶ added in v1.0.0
IsNoTokenError reports whether the error is that there is no token.
Types ¶
type CORSConfig ¶ added in v1.5.0
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 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 ¶ added in v1.5.0
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 Flat ¶ added in v1.0.0
func Flat(befores, afters []ship.Handler) Middleware
Flat returns a flat middleware, which will execute the handlers in turn, and terminate the rest handlers and return the error if there is an error returned by a certain handler.
befores will be executed before handling the request, and afters is after handling the request.
Example
beforeLog := func(ctx *ship.Context) error { ctx.Logger().Info("before handling the request") return nil } afterLog := func(ctx *ship.Context) error { ctx.Logger().Info("after handling the request") return nil } handler := func(ctx *ship.Context) error { ctx.Logger().Info("handling the request") return nil }) router := ship.New() router.Use(Flat([]ship.Handler{beforeLog}, []ship.Handler{afterLog})) router.R("/").GET(handler)
You can pass the error by the ctx.SetError(err). For example,
handler := func(ctx *ship.Context) error { // ... ctx.Err = err return nil }) afterLog := func(ctx *ship.Context) (err error) { if ctx.Err != nil { ctx.Logger().Info("after handling the request: %s", ctx.Err) ctx.Err = nil // Avoid to handle the error repeatedly by other middlewares. } else { ctx.Logger().Info("after handling the request") } return }
func Gzip ¶
func Gzip(level ...int) Middleware
Gzip returns a middleware to compress the response body by GZIP.
func Logger ¶
func Logger(now ...func() time.Time) Middleware
Logger returns a new logger middleware that will log the request.
By default getTime is time.Now().
Notice: If using this middleware, you should configure Ship with ship.DisableErrorLog(true) to disable the default error log. For example,
app := ship.New(ship.DisableErrorLog(true))
Or
app := ship.New() app.Configure(ship.DisableErrorLog(true))
func Matchers ¶ added in v1.0.0
Matchers returns a middleware to execute the matchers, which will execute those matchers in turn. If a certain matcher returns an error, it will return a HTTPError with 404 and the error by default. But you can appoint a error handler.
func MaxRequests ¶ added in v1.0.0
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(handle ...func(*ship.Context, interface{})) Middleware
Recover returns a middleware to wrap the panic.
Change:
- Ignore the argument handle. In order to keep the backward compatibility, we don't remove it until the next major version.
- This middleware only recovers the panic and returns it as an error.
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 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 ResetResponse ¶
func ResetResponse(reset func(http.ResponseWriter) http.ResponseWriter) Middleware
ResetResponse wraps and reset the response.
func SetCtxHandler ¶ added in v1.0.0
func SetCtxHandler(h func(*ship.Context, ...interface{}) error) Middleware
SetCtxHandler sets the context handler to h.
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 ¶
TokenFunc stands for a function to get a token from the request context.
func GetTokenFromForm ¶ added in v1.0.0
GetTokenFromForm is used to get the token from the request FORM body.
func GetTokenFromHeader ¶ added in v1.0.0
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 ¶ added in v1.0.0
GetTokenFromQuery is used to get the token from the request URL query.
type TokenValidator ¶
TokenValidator stands for a validator to validate whether a token is valid.