gin

package module
v0.0.0-...-0807185 Latest Latest
Warning

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

Go to latest
Published: Jun 26, 2023 License: Apache-2.0 Imports: 4 Imported by: 13

Documentation

Overview

This package provides Sentinel middleware for Gin.

Users may register SentinelMiddleware to the Gin server, like.

import (
	sentinelPlugin "github.com/sentinel-group/sentinel-go-adapters/gin"
	"github.com/gin-gonic/gin"
)

r := gin.New()
r.Use(sentinelPlugin.SentinelMiddleware())

The plugin extracts "HttpMethod:FullPath" as the resource name by default (e.g. GET:/foo/:id). Users may provide customized resource name extractor when creating new SentinelMiddleware (via options).

Fallback logic: the plugin will return "429 Too Many Requests" status code if current request is blocked by Sentinel rules. Users may also provide customized fallback logic via WithBlockFallback(handler) options.

Example
r := gin.New()
r.Use(
	SentinelMiddleware(
		// customize resource extractor if required
		// method_path by default
		WithResourceExtractor(func(ctx *gin.Context) string {
			return ctx.GetHeader("X-Real-IP")
		}),
		// customize block fallback if required
		// abort with status 429 by default
		WithBlockFallback(func(ctx *gin.Context) {
			ctx.AbortWithStatusJSON(400, map[string]interface{}{
				"err":  "too many request; the quota used up",
				"code": 10222,
			})
		}),
	),
)

r.GET("/test", func(c *gin.Context) {})
_ = r.Run(":0")
Output:

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func SentinelMiddleware

func SentinelMiddleware(opts ...Option) gin.HandlerFunc

SentinelMiddleware returns new gin.HandlerFunc Default resource name is {method}:{path}, such as "GET:/api/users/:id" Default block fallback is returning 429 code Define your own behavior by setting options

Types

type Option

type Option func(*options)

func WithBlockFallback

func WithBlockFallback(fn func(ctx *gin.Context)) Option

WithBlockFallback sets the fallback handler when requests are blocked.

func WithResourceExtractor

func WithResourceExtractor(fn func(*gin.Context) string) Option

WithResourceExtractor sets the resource extractor of the web requests.

Jump to

Keyboard shortcuts

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