middlewares

package module
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Jan 12, 2023 License: MIT Imports: 16 Imported by: 1

README

gin-middlewares

separated from go-utils/gin-middlewares

Documentation

Overview

Package middlewares useful middlewares

Package middlewares some useful middlewares for gin

Index

Examples

Constants

This section is empty.

Variables

View Source
var GinCtxKey ctxkey = "gin"

GinCtxKey key of gin ctx that saved in request.context

View Source
var Logger log.Logger

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 NewHTTPMetricSrv

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

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

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) SetAuthHeader

func (a *Auth) SetAuthHeader(ctx context.Context, optfs ...SetAuthHeaderOption) (string, error)

SetAuthHeader set jwt token to cookies

func (*Auth) Sign

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

Sign sign jwt token

type AuthOptFunc

type AuthOptFunc func(*Auth) error

AuthOptFunc auth option

func WithAuthJWT

func WithAuthJWT(jwt gjwt.JWT) AuthOptFunc

WithAuthJWT set jwt lib

type LoggerMwOptFunc

type LoggerMwOptFunc func(opt *loggerMwOpt)

LoggerMwOptFunc logger options

func WithLevel added in v4.0.1

func WithLevel(level glog.Level) LoggerMwOptFunc

WithLevel (optional) set log level

only support debug/info

default to debug

func WithLogger

func WithLogger(logger glog.Logger) LoggerMwOptFunc

WithLogger set default logger

func WithLoggerCtxKey

func WithLoggerCtxKey(key string) LoggerMwOptFunc

WithLoggerCtxKey embedded logger into context

func WithLoggerMwColored

func WithLoggerMwColored() LoggerMwOptFunc

WithLoggerMwColored enable coloered log

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

Directories

Path Synopsis
example
metrics/router
Package main run metric server as gin's router
Package main run metric server as gin's router
metrics/standalone
Package main run metric server
Package main run metric server

Jump to

Keyboard shortcuts

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