middlewares

package module
v2.1.2 Latest Latest
Warning

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

Go to latest
Published: Sep 7, 2022 License: MIT Imports: 14 Imported by: 1

README

gin-middlewares

separated from go-utils/gin-middlewares

Documentation

Overview

Package middlewares useful middlewares

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 NewHTTPMetricSrv

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

NewHTTPMetricSrv start new gin server with metrics api

func NewLoggerMiddleware added in v2.1.0

func NewLoggerMiddleware(optfs ...LoggerMwOptFunc) gin.HandlerFunc

NewLoggerMiddleware middleware to logging

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"

	glog "github.com/Laisky/go-utils/v2/log"
	"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 {
		glog.Shared.Panic("try to init gin auth got error", zap.Error(err))
	}

	ctx := &gin.Context{}
	uc := &UserClaims{}
	if err := auth.GetUserClaims(ctx, uc); err != nil {
		glog.Shared.Warn("user invalidate", zap.Error(err))
	} else {
		glog.Shared.Info("user validate", zap.String("uid", uc.Subject))
	}

	if _, err = auth.SetLoginCookie(ctx, WithAuthClaims(uc)); err != nil {
		glog.Shared.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 {
		glog.Shared.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) SetLoginCookie

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

SetLoginCookie set jwt token to cookies

func (*Auth) Sign

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

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

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

func WithAuthJWT(jwt gjwt.JWT) AuthOptFunc

WithAuthJWT set jwt lib

type LoggerMwOptFunc

type LoggerMwOptFunc func(opt *loggerMwOpt)

func WithLogger added in v2.1.0

func WithLogger(logger glog.Logger) LoggerMwOptFunc

func WithLoggerCtxKey added in v2.1.0

func WithLoggerCtxKey(key string) LoggerMwOptFunc

func WithLoggerMwColored

func WithLoggerMwColored() LoggerMwOptFunc

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/router
Package main standalone router
Package main standalone router

Jump to

Keyboard shortcuts

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