middlewares

package
v1.9.1 Latest Latest
Warning

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

Go to latest
Published: Nov 8, 2019 License: MIT Imports: 10 Imported by: 0

Documentation

Index

Examples

Constants

View Source
const (
	// AuthTokenName jwt token cookie name
	AuthTokenName = "token"
	// AuthUserIDCtxKey key of user ID in jwt token
	AuthUserIDCtxKey = "auth_uid"
	// AuthTokenAge how long live
	AuthTokenAge = 3600 * 24 * 7 // 7days
)

Variables

View Source
var GinCtxKey utils.CtxKeyT

GinCtxKey key of gin ctx that saved in request.context

Functions

func BindPrometheus added in v1.4.1

func BindPrometheus(s *gin.Engine)

BindPrometheus bind prometheus endpoint.

func EnableMetric added in v1.8.0

func EnableMetric(srv *gin.Engine, options ...MetricsOptFunc)

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 LoggerMiddleware

func LoggerMiddleware(ctx *gin.Context)

LoggerMiddleware middleware to logging

func StartHTTPMetricSrv added in v1.8.0

func StartHTTPMetricSrv(ctx context.Context, options ...MetricsOptFunc)

StartHTTPMetricSrv start new gin server with metrics api

Types

type Auth

type Auth struct {
	*AuthCfg
	// contains filtered or unexported fields
}

Auth JWT cookie based token generator and validator. Cookie looks like <AuthTokenName>:`{<AuthUserIDCtxKey>: "xxxx"}`

Example
package main

import (
	"net/http"

	middlewares "github.com/Laisky/go-utils/gin-middlewares"
	"github.com/Laisky/zap"

	"github.com/gin-gonic/gin"

	"github.com/Laisky/go-utils"
)

type User struct{}

func (u *User) GetPayload() map[string]interface{} {
	return map[string]interface{}{"a": "b"}
}

func (u *User) GetID() string {
	return "123"
}

func main() {
	cfg := middlewares.NewAuthCfg("f32lifj2f32fj")
	auth, err := middlewares.NewAuth(cfg)
	if err != nil {
		utils.Logger.Panic("try to init gin auth got error", zap.Error(err))
	}

	ctx := &gin.Context{}
	uid, err := auth.ValidateAndGetUID(ctx)
	if err != nil {
		utils.Logger.Warn("user invalidate", zap.Error(err))
	} else {
		utils.Logger.Info("user validate", zap.String("uid", uid.Hex()))
	}

	user := &User{}
	if err = auth.SetLoginCookie(ctx, user, middlewares.NewCookieCfg()); err != nil {
		utils.Logger.Error("try to set cookie got error", zap.Error(err))
	}

	Server := gin.New()
	Server.Handle("ANY", "/authorized/", middlewares.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(cfg *AuthCfg) (*Auth, error)

NewAuth create new Auth with AuthCfg

func (*Auth) SetLoginCookie

func (a *Auth) SetLoginCookie(ctx context.Context, user UserItf, cfg *CookieCfg) (err error)

SetLoginCookie set jwt token to cookies

func (*Auth) ValidateAndGetUID

func (a *Auth) ValidateAndGetUID(ctx context.Context) (uid bson.ObjectId, err error)

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

type AuthCfg

type AuthCfg struct {
	Secret        string
	CookieExpires time.Duration
}

AuthCfg configuration of Auth

func NewAuthCfg

func NewAuthCfg(secret string) *AuthCfg

NewAuthCfg return AuthCfg with default configuration

type CookieCfg added in v1.4.1

type CookieCfg struct {
	MaxAge           int // seconds
	Path, Host       string
	Secure, HTTPOnly bool
}

CookieCfg configuration of cookies

func NewCookieCfg added in v1.4.1

func NewCookieCfg() *CookieCfg

NewCookieCfg create default cookie configuration

type MetricOption added in v1.8.0

type MetricOption struct {
	// contains filtered or unexported fields
}

MetricOption metric option argument

func NewMetricOption added in v1.8.0

func NewMetricOption() *MetricOption

NewMetricOption create new default option

type MetricsOptFunc added in v1.8.0

type MetricsOptFunc func(*MetricOption)

MetricsOptFunc option of metrics

func WithMetricAddr added in v1.8.0

func WithMetricAddr(addr string) MetricsOptFunc

WithMetricAddr set option addr

func WithMetricGraceWait added in v1.8.0

func WithMetricGraceWait(wait time.Duration) MetricsOptFunc

WithMetricGraceWait set wating time after graceful shutdown

func WithPprofPath added in v1.8.0

func WithPprofPath(path string) MetricsOptFunc

WithPprofPath set option pprofPath

type UserItf

type UserItf interface {
	GetPayload() map[string]interface{}
	GetID() string
}

UserItf User model interface

Jump to

Keyboard shortcuts

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