middlewares

package module
v1.3.0 Latest Latest
Warning

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

Go to latest
Published: Dec 20, 2021 License: MIT Imports: 12 Imported by: 1

README

gin-middlewares

separated from go-utils/gin-middlewares

Documentation

Index

Examples

Constants

This section is empty.

Variables

View Source
var GinCtxKey utils.CtxKeyT

GinCtxKey key of gin ctx that saved in request.context

Functions

func BindPrometheus

func BindPrometheus(s *gin.Engine)

BindPrometheus bind prometheus endpoint.

func EnableMetric

func EnableMetric(srv *gin.Engine, 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

func GetGinCtxFromStdCtx(ctx context.Context) *gin.Context

GetGinCtxFromStdCtx get gin context from standard request.context by GinCtxKey

func GetLoggerMiddleware added in v1.2.0

func GetLoggerMiddleware(logger *gutils.LoggerType) gin.HandlerFunc

GetLoggerMiddleware middleware to logging

func NewHTTPMetricSrv added in v1.2.0

func NewHTTPMetricSrv(ctx context.Context, options ...MetricsOptFunc) (srv *http.Server, err error)

NewHTTPMetricSrv start new gin server with metrics api

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/go-utils"
	"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 {
		utils.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 {
		utils.Logger.Warn("user invalidate", zap.Error(err))
	} else {
		utils.Logger.Info("user validate", zap.String("uid", uc.Subject))
	}

	if err = auth.SetLoginCookie(ctx, uc); err != nil {
		utils.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 {
		utils.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 added in v1.1.0

func (a *Auth) GetUserClaims(ctx context.Context, claims jwt.Claims) (err error)

GetUserClaims get token from request.ctx then validate and return userid

func (*Auth) SetLoginCookie deprecated

func (a *Auth) SetLoginCookie(ctx context.Context, claims jwt.Claims, opts ...AuthCookieOptFunc) (err error)

SetLoginCookie set jwt token to cookies

Deprecated: use SetLoginCookiev2 instead

func (*Auth) SetLoginCookiev2 added in v1.3.0

func (a *Auth) SetLoginCookiev2(ctx context.Context,
	opts ...AuthCookieOptFunc) (token string, err error)

SetLoginCookiev2 set jwt token to cookies

func (*Auth) Sign added in v1.3.0

func (a *Auth) Sign(claim jwt.Claims) (string, error)

Sign sign jwt token

type AuthCookieOptFunc

type AuthCookieOptFunc func(*authCookieOption) error

AuthCookieOptFunc auth cookie options

func WithAuthClaims added in v1.3.0

func WithAuthClaims(claims jwt.Claims) AuthCookieOptFunc

WithAuthClaims set claims that will used to sign jwt token

func WithAuthCookieHTTPOnly

func WithAuthCookieHTTPOnly(httpOnly bool) AuthCookieOptFunc

WithAuthCookieHTTPOnly set auth cookie's HTTPOnly

func WithAuthCookieHost

func WithAuthCookieHost(host string) AuthCookieOptFunc

WithAuthCookieHost set auth cookie's host

func WithAuthCookieMaxAge

func WithAuthCookieMaxAge(maxAge int) AuthCookieOptFunc

WithAuthCookieMaxAge set auth cookie's maxAge

func WithAuthCookiePath

func WithAuthCookiePath(path string) AuthCookieOptFunc

WithAuthCookiePath set auth cookie's path

func WithAuthCookieSecure

func WithAuthCookieSecure(secure bool) AuthCookieOptFunc

WithAuthCookieSecure set auth cookie's secure

func WithAuthToken added in v1.3.0

func WithAuthToken(token string) AuthCookieOptFunc

WIthAuthToken set jwt token to response

type AuthOptFunc

type AuthOptFunc func(*Auth) error

AuthOptFunc auth option

func WithAuthCookieExpireDuration

func WithAuthCookieExpireDuration(d time.Duration) AuthOptFunc

WithAuthCookieExpireDuration set auth cookie expiration

func WithAuthJWT added in v1.3.0

func WithAuthJWT(jwt *utils.JWT) AuthOptFunc

WithAuthJWT set jwt lib

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

Directories

Path Synopsis
example
metrics module

Jump to

Keyboard shortcuts

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