goframe

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

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

Go to latest
Published: Jul 2, 2025 License: Apache-2.0 Imports: 4 Imported by: 0

Documentation

Overview

Package goframe provides Sentinel middleware for GoFrame.

Users may register SentinelMiddleware to the GoFrame server, like:

import (
	sentinelPlugin "github.com/your-repo/goframe-sentinel-adapter"
	"github.com/gogf/gf/v2/frame/g"
	"github.com/gogf/gf/v2/net/ghttp"
)

s := g.Server()
s.Use(ghttp.MiddlewareHandlerFunc(sentinelPlugin.SentinelMiddleware()))

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

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

Example
s := g.Server()
s.Use(
	SentinelMiddleware(
		// customize resource extractor if required
		WithResourceExtractor(func(r *ghttp.Request) string {
			if res, ok := r.Header["X-Real-IP"]; ok && len(res) > 0 {
				return res[0]
			}
			return ""
		}),
		// customize block fallback if required
		WithBlockFallback(func(r *ghttp.Request) {
			r.Response.WriteHeader(400)
			r.Response.WriteJson(map[string]interface{}{
				"err":  "too many requests; the quota used up",
				"code": 10222,
			})
		}),
	),
)

s.Group("/", func(group *ghttp.RouterGroup) {
	group.GET("/test", func(r *ghttp.Request) {
		r.Response.Write("hello sentinel")
	})
})

s.SetPort(8199)

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

func SentinelMiddleware

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

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

Types

type Option

type Option func(*options)

func WithBlockFallback

func WithBlockFallback(fn func(r *ghttp.Request)) Option

WithBlockFallback sets the fallback handler when requests are blocked.

func WithResourceExtractor

func WithResourceExtractor(fn func(*ghttp.Request) 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