Documentation
¶
Overview ¶
Package middlewares useful middlewares
Package middlewares some useful middlewares for gin
Index ¶
- Constants
- Variables
- func BackgroundCtx(c *gin.Context) context.Context
- func BindPrometheus(s gin.IRouter)
- func Ctx(c *gin.Context) context.Context
- func CtxLock(ctx context.Context) error
- func CtxRLock(ctx context.Context) error
- func CtxRUnlock(ctx context.Context) error
- func CtxUnlock(ctx context.Context) error
- func EnableMetric(srv gin.IRouter, options ...MetricsOptFunc) (err error)
- func FromStd(handler http.HandlerFunc) gin.HandlerFunc
- func GetGinCtxFromStdCtx(ctx context.Context) (*gin.Context, bool)
- func GetLockFromCtx(ctx context.Context) (*sync.RWMutex, error)
- func GetLogger(ctx context.Context) (logger glog.Logger)
- func LockableMw() gin.HandlerFunc
- func NewHTTPMetricSrv(ctx context.Context, options ...MetricsOptFunc) (srv *http.Server, err error)
- func NewLoggerMiddleware(optfs ...LoggerMwOptFunc) gin.HandlerFunc
- func SetCookie(ctx *gin.Context, name, value string, opts ...SetCookieOption) (err error)
- func SetLogger(ctx context.Context, logger glog.Logger) context.Context
- func TraceID(ctx *gin.Context) (gutils.JaegerTracingID, error)
- type Auth
- type AuthOptFunc
- type LoggerMwOptFunc
- type MetricsOptFunc
- type SetAuthHeaderOption
- type SetCookieOption
Examples ¶
Constants ¶
const ( // CtxKeyGin key of gin ctx that saved in request.context CtxKeyGin ctxkey = "@laisky-gmw:gin" CtxKeyLock ctxkey = "@laisky-gmw:lock" )
Variables ¶
var Logger log.Logger
Functions ¶
func BackgroundCtx ¶
BackgroundCtx get background context from gin.Context
func CtxRUnlock ¶
CtxRUnlock unlock the lock in gin context
func EnableMetric ¶
func EnableMetric(srv gin.IRouter, options ...MetricsOptFunc) (err error)
EnableMetric enable metrics for exsits gin server
func FromStd ¶
func FromStd(handler http.HandlerFunc) gin.HandlerFunc
FromStd convert std handler to gin.Handler, with gin context embedded
func GetGinCtxFromStdCtx ¶
GetGinCtxFromStdCtx get gin context from standard request.context by GinCtxKey
func GetLockFromCtx ¶
GetLockFromCtx get lock from gin context
func LockableMw ¶
func LockableMw() gin.HandlerFunc
LockableMw create a gin middleware that add a lock to gin context
func NewHTTPMetricSrv ¶
NewHTTPMetricSrv start new gin server with metrics api
func NewLoggerMiddleware ¶
func NewLoggerMiddleware(optfs ...LoggerMwOptFunc) gin.HandlerFunc
NewLoggerMiddleware middleware to logging
func SetCookie ¶
func SetCookie(ctx *gin.Context, name, value string, opts ...SetCookieOption) (err error)
SetCookie set jwt token to cookies
Types ¶
type Auth ¶
type Auth struct {
// contains filtered or unexported fields
}
Auth JWT cookie based token generator and validator. Cookie looks like <defaultAuthTokenName>:`{<defaultAuthUserIDCtxKey>: "xxxx"}`
Example ¶
package main
import (
"net/http"
"github.com/Laisky/zap"
"github.com/gin-gonic/gin"
"github.com/golang-jwt/jwt/v4"
)
type UserClaims struct {
jwt.StandardClaims
}
func main() {
auth, err := NewAuth([]byte("f32lifj2f32fj"))
if err != nil {
Logger.Panic("try to init gin auth got error", zap.Error(err))
}
ctx := &gin.Context{}
uc := &UserClaims{}
if err := auth.GetUserClaims(ctx, uc); err != nil {
Logger.Warn("user invalidate", zap.Error(err))
} else {
Logger.Info("user validate", zap.String("uid", uc.Subject))
}
if _, err = auth.SetAuthHeader(ctx, WithSetAuthHeaderClaim(uc)); err != nil {
Logger.Error("try to set cookie got error", zap.Error(err))
}
Server := gin.New()
Server.Handle("ANY", "/authorized/", FromStd(DemoHandle))
}
func DemoHandle(w http.ResponseWriter, r *http.Request) {
// middlewares
if _, err := w.Write([]byte("hello")); err != nil {
Logger.Error("http write", zap.Error(err))
}
}
Output:
func NewAuth ¶
func NewAuth(secret []byte, opts ...AuthOptFunc) (a *Auth, err error)
NewAuth create new Auth
func (*Auth) GetUserClaims ¶
GetUserClaims get token from request.ctx then validate and return userid
func (*Auth) SetAuthHeader ¶
SetAuthHeader set jwt token to cookies
type AuthOptFunc ¶
AuthOptFunc auth option
type LoggerMwOptFunc ¶
type LoggerMwOptFunc func(opt *loggerMwOpt)
LoggerMwOptFunc logger options
func WithLevel ¶
func WithLevel(level string) LoggerMwOptFunc
WithLevel (optional) set log level
only support debug/info
default to debug
func WithLoggerMwColored ¶
func WithLoggerMwColored() LoggerMwOptFunc
WithLoggerMwColored enable coloered log
func WithTracingCtxKey ¶
func WithTracingCtxKey(key string) LoggerMwOptFunc
WithTracingCtxKey embedded traceID into context
type MetricsOptFunc ¶
type MetricsOptFunc func(*metricOption) error
MetricsOptFunc option of metrics
func WithMetricAddr ¶
func WithMetricAddr(addr string) MetricsOptFunc
WithMetricAddr set option addr
func WithMetricGraceWait ¶
func WithMetricGraceWait(wait time.Duration) MetricsOptFunc
WithMetricGraceWait set wating time after graceful shutdown
func WithPprofPath ¶
func WithPprofPath(path string) MetricsOptFunc
WithPprofPath set option pprofPath
type SetAuthHeaderOption ¶
type SetAuthHeaderOption func(*setAuthHeaderOption) error
func WithSetAuthHeaderClaim ¶
func WithSetAuthHeaderClaim(claim jwt.Claims) SetAuthHeaderOption
func WithSetAuthHeaderToken ¶
func WithSetAuthHeaderToken(token string) SetAuthHeaderOption
type SetCookieOption ¶
type SetCookieOption func(*setCookieOption) error
SetCookieOption auth cookie options
func WithCookieHTTPOnly ¶
func WithCookieHTTPOnly(httpOnly bool) SetCookieOption
WithCookieHTTPOnly set auth cookie's HTTPOnly
func WithCookieHost ¶
func WithCookieHost(host string) SetCookieOption
WithCookieHost set auth cookie's host
func WithCookieMaxAge ¶
func WithCookieMaxAge(maxAge int) SetCookieOption
WithCookieMaxAge set auth cookie's maxAge
func WithCookiePath ¶
func WithCookiePath(path string) SetCookieOption
WithCookiePath set auth cookie's path
func WithCookieSecure ¶
func WithCookieSecure(secure bool) SetCookieOption
WithCookieSecure set auth cookie's secure
Source Files
¶
Directories
¶
| Path | Synopsis |
|---|---|
|
example
|
|
|
metrics/router
command
Package main run metric server as gin's router
|
Package main run metric server as gin's router |
|
metrics/standalone
command
Package main run metric server
|
Package main run metric server |