ginqq

package module
v0.2.0 Latest Latest
Warning

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

Go to latest
Published: May 28, 2025 License: MIT Imports: 21 Imported by: 0

README

个性化Gin框架(ginqq)

简介

本项目是一个基于Gin框架二次开发的框架,提供了一些部门通用的功能和扩展。

设计原则
  • 开箱即用:内置系统级可观测性能力、API规范化能力,业务研发只需要关注业务逻辑
  • 最小入侵:不更改或尽可能少更改暴露的公共方法,对业务代码极少入侵,历史项目无缝切换,无学习成本
  • 功能可控:通过初始化参数控制各个功能开关,默认开启
  • 可扩展性:不更改已有代码的基础上支持新增功能,如鉴权、限流
功能
功能类型 功能清单 说明
API规范化 - API规范化(服务端、客户端)
- 安全过滤
- API规范内容自动补全、不合规调用拦截
- 包含XSS、SQL注入、CSRF等安全过滤逻辑
系统级可观测性 - 日志
- 监控
- 链路
- 内、外部流水
- 接口监控
- 接口链路

快速开始

版本要求
  • 推荐 Go 1.23+
安装
go get github.com/channel07/ginqq

简单使用

默认配置

package main

import (
	gin "github.com/channel07/ginqq"
	"net/http"
)

func main() {
	r := gin.Default("A186010101", "channel07-ginqq")

	g := r.Group("/api")
	g.GET("/hello", func(c *gin.Context) {
		traceId := c.GetTraceId()
		http.Get("http://www.baidu.com")
		c.JSON(http.StatusOK, gin.H{"message": "Hello from ginqq!", "traceId": traceId})
	})

	r.Run(":8080")
}

个性化配置

package main

import (
	gin "github.com/channel07/ginqq"
	"net/http"
)

func main() {
	cfg := &gin.Config{
		SvcCode: "A186010101",
		AppName: "channel07-ginqq",
		MetricsConfig: &gin.MetricsConfig{
			Buckets: []float64{100, 200, 500, 1000, 2000, 3000, 5000, 10000},
			CustomLabels: map[string]string{
				"operate_type": "OPERATE_TYPE",
			},
		},
		HttpClientEnhanceConfig: &gin.HttpClientEnhanceConfig{
			Transport: http.DefaultTransport,
		},
	}
	r := gin.NewEngineWithConfig(cfg)

	r.GET("/hello", func(c *gin.Context) {
		c.JSON(http.StatusOK, gin.H{"message": "Hello from ginqq!"})
	})

	r.Run(":8080")
}

文档

Documentation

Overview

Package ginqq 自定义的context,用于传递系统上下文信息,如服务编码,traceId等

Index

Constants

View Source
const (
	XTraceID         = "Trace-ID"
	XTransactionID   = "Transaction-ID"
	XFCode           = "User-Agent"
	XMethodCode      = "Method-Code"
	XMethodName      = "Method-Name"
	XResponsePayload = "Response-Payload"
)

Variables

This section is empty.

Functions

func ApiStandardServerMiddleware

func ApiStandardServerMiddleware() func(*Context)

func CrossJson added in v0.2.0

func CrossJson(data interface{}) (deserialization interface{})

func DispatchTransactionLog added in v0.2.0

func DispatchTransactionLog(c *Context)

DispatchTransactionLog 调度内部流水日志,作为中间件使用。

func FuzzyGet added in v0.2.0

func FuzzyGet(data interface{}, key string) string

FuzzyGet 在嵌套数据结构中模糊查找键并返回值。

func FuzzyGetMany added in v0.2.0

func FuzzyGetMany(data interface{}, keys []string) (result string)

func GetHostIP added in v0.2.0

func GetHostIP() (string, error)

GetHostIP 获取主机的非回环 IPv4 地址。

func HttpEnhance

func HttpEnhance(cfg *HttpClientEnhanceConfig)

func MethodCode added in v0.2.0

func MethodCode(I string) func(*Context)

MethodCode 是一个中间件,用于设置接口编码。

func MetricsServerMiddleware

func MetricsServerMiddleware() func(*Context)

func SecurityMiddleware

func SecurityMiddleware() func(*Context)

func TracingServerMiddleware

func TracingServerMiddleware() func(*Context)

func TransactionLogMiddleware added in v0.2.0

func TransactionLogMiddleware() func(*Context)

TransactionLogMiddleware 流水日志中间件。

Types

type ChainBuilder

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

ChainBuilder 链式构建器,用于构建中间件链,

func NewChainBuilder

func NewChainBuilder(base http.RoundTripper) *ChainBuilder

func (*ChainBuilder) Build

func (b *ChainBuilder) Build() http.RoundTripper

Build 返回调用链头指针

func (*ChainBuilder) Use

func (b *ChainBuilder) Use(middlewares ...http.RoundTripper) *ChainBuilder

Use 构建中间件链表,头插法

type Config

type Config struct {
	SvcCode string // 服务编码(大写)
	AppName string // 应用名称(小写,以下划线拼接)

	// 功能开关&配置
	// 服务端系统可观测性
	DisableMetrics        bool
	MetricsConfig         *MetricsConfig
	DisableTracing        bool // 链路
	DisableTransactionLog bool // 内部流水

	// 服务端API规范化
	DisableApiStandardServer bool // 服务端API规范调用&校验拦截

	// Http客户端配置
	DisableHttpClientEnhance bool // http增强
	HttpClientEnhanceConfig  *HttpClientEnhanceConfig

	DisableProgramLog bool // 是否禁用程序日志

	LogConfig *LogConfig
}

func (*Config) GetPlayCode added in v0.2.0

func (c *Config) GetPlayCode() string

type Context

type Context struct {
	*gin.Context
}

func Wrap

func Wrap(c *gin.Context) *Context

func (*Context) AsciiJSON added in v0.2.0

func (c *Context) AsciiJSON(code int, obj interface{})

func (*Context) GetFCode added in v0.2.0

func (c *Context) GetFCode() string

func (*Context) GetMethodCode

func (c *Context) GetMethodCode() string

func (*Context) GetMethodName added in v0.2.0

func (c *Context) GetMethodName() string

func (*Context) GetRawDataReusable added in v0.2.0

func (c *Context) GetRawDataReusable() ([]byte, error)

GetRawDataReusable get the request-body and reset it.

func (*Context) GetResponsePayload added in v0.2.0

func (c *Context) GetResponsePayload() interface{}

func (*Context) GetTraceID added in v0.2.0

func (c *Context) GetTraceID() string

func (*Context) GetTransactionID added in v0.2.0

func (c *Context) GetTransactionID() string

func (*Context) IndentedJSON added in v0.2.0

func (c *Context) IndentedJSON(code int, obj interface{})

func (*Context) JSON added in v0.2.0

func (c *Context) JSON(code int, obj interface{})

func (*Context) JSONP added in v0.2.0

func (c *Context) JSONP(code int, obj interface{})

func (*Context) PureJSON added in v0.2.0

func (c *Context) PureJSON(code int, obj interface{})

func (*Context) SecureJSON added in v0.2.0

func (c *Context) SecureJSON(code int, obj interface{})

type GinQQ

type GinQQ struct {
	*gin.Engine
	Config *Config
}

GinQQ 自定义框架结构体。

func Default

func Default(svcCode, appName string) *GinQQ

Default 创建默认的 GinQQ 实例。

func NewEngineWithConfig

func NewEngineWithConfig(config *Config) *GinQQ

func (*GinQQ) DELETE

func (g *GinQQ) DELETE(relativePath string, handlers ...func(*Context))

func (*GinQQ) GET

func (g *GinQQ) GET(relativePath string, handlers ...func(*Context))

func (*GinQQ) Group

func (g *GinQQ) Group(relativePath string, handlers ...func(*Context)) *RouterGroup

Group 返回自定义 RouterGroup 。

func (*GinQQ) POST

func (g *GinQQ) POST(relativePath string, handlers ...func(*Context))

func (*GinQQ) PUT

func (g *GinQQ) PUT(relativePath string, handlers ...func(*Context))

func (*GinQQ) Use

func (g *GinQQ) Use(handlers ...func(*Context))

type H

type H gin.H

type HttpClientEnhanceConfig

type HttpClientEnhanceConfig struct {
	Transport                http.RoundTripper // 基础transport,默认使用http.DefaultTransport,可自定义transport设置连接池参数、超时时间等
	DisableSkipVerify        bool              // 跳过证书认证,默认跳过 TODO 后续增加证书认证体系
	DisableApiStandardClient bool              // 客户端API规范调用&校验拦截
	DisableTransactionLog    bool              // 外部流水
}

type LevelHook added in v0.2.0

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

LevelHook 分发不同级别的日志到不同文件

func (*LevelHook) Fire added in v0.2.0

func (h *LevelHook) Fire(entry *logrus.Entry) error

func (*LevelHook) Levels added in v0.2.0

func (h *LevelHook) Levels() []logrus.Level

type LogConfig added in v0.2.0

type LogConfig struct {
	// LogDir 是日志文件的目录,文件名自动生成。备份日志文件将保留在同一目录下。
	// 默认为 "/app/logs"(如果你的系统是 Windows 则默认为 "C:\\BllLogs\\<Config.SvcCode>_<Config.AppName>")。
	LogDir string

	// MaxSize 是日志文件轮转前的最大大小(以兆字节为单位),默认为 1024MB。
	MaxSize int

	// MaxAge 是根据文件名中编码的时间戳保留旧日志文件的最大天数。
	// 注意:一天定义为24小时,可能因夏令时、闰秒等因素与日历日不完全对应。
	// 默认不根据时间删除旧日志文件。
	MaxAge int

	// MaxBackups 是要保留的旧日志文件的最大数量,默认为 7。
	MaxBackups int

	// LocalTime 确定备份文件名中的时间戳是否使用计算机本地时间,默认使用 UTC 时间。
	LocalTime bool

	// Compress 确定轮转的日志文件是否使用 gzip 压缩,默认不压缩。
	Compress bool

	// RotationInterval 是日志轮转的最大时间间隔,默认为 1 天。
	// 如果自上次轮转经过的时间超过该间隔,即使文件大小未达到 MaxSize 也会触发轮转。
	// 最小推荐值为 1 分钟。如果设为 0 则禁用基于时间的轮转。
	//
	// 示例 RotationInterval = time.Hour * 24 表示每天轮转日志。
	RotationInterval time.Duration
}

type LoggingTripper

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

func NewLoggingTripper

func NewLoggingTripper() *LoggingTripper

func (*LoggingTripper) RoundTrip

func (l *LoggingTripper) RoundTrip(req *http.Request) (*http.Response, error)

func (*LoggingTripper) SetNext

func (l *LoggingTripper) SetNext(next http.RoundTripper)

type LoggingTripper2

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

LoggingTripper2 中间件示例,需要实现RoundTrip处理接口,SetNext设置下个中间接口

func NewLoggingTripper2

func NewLoggingTripper2() *LoggingTripper2

func (*LoggingTripper2) RoundTrip

func (l *LoggingTripper2) RoundTrip(req *http.Request) (*http.Response, error)

func (*LoggingTripper2) SetNext

func (l *LoggingTripper2) SetNext(next http.RoundTripper)

type MetricsConfig

type MetricsConfig struct {
	// bucket
	Buckets []float64 // 桶设置,单位毫秒,默认 [100, 200, 500, 1000, 2000, 3000, 5000, 10000]
	// 自定义标签,key:标签名,value:ctx中获取标签值的方法名,如:ctx.Get("operate_type")
	CustomLabels map[string]string
}

type PlainFormatter added in v0.2.0

type PlainFormatter struct{}

func (*PlainFormatter) Format added in v0.2.0

func (f *PlainFormatter) Format(entry *logrus.Entry) ([]byte, error)

type RouterGroup

type RouterGroup struct {
	*gin.RouterGroup
}

RouterGroup GinQQ 路由组,强制处理函数接收自定义的 *Context 。

func (*RouterGroup) DELETE

func (g *RouterGroup) DELETE(relativePath string, handlers ...func(*Context))

func (*RouterGroup) GET

func (g *RouterGroup) GET(relativePath string, handlers ...func(*Context))

func (*RouterGroup) POST

func (g *RouterGroup) POST(relativePath string, handlers ...func(*Context))

func (*RouterGroup) PUT

func (g *RouterGroup) PUT(relativePath string, handlers ...func(*Context))

type TransactionLog added in v0.2.0

type TransactionLog struct {
	AppName             string `json:"app_name"`
	Level               string `json:"level"`
	LogTime             string `json:"log_time"`
	Logger              string `json:"logger"`
	Thread              string `json:"thread"`
	TransactionID       string `json:"transaction_id"`
	DialogType          string `json:"dialog_type"`
	Address             string `json:"address"`
	FCode               string `json:"fcode"`
	TCode               string `json:"tcode"`
	MethodCode          string `json:"method_code"`
	MethodName          string `json:"method_name"`
	HTTPMethod          string `json:"http_method"`
	RequestTime         string `json:"request_time"`
	RequestHeaders      string `json:"request_headers"`
	RequestPayload      string `json:"request_payload"`
	ResponseTime        string `json:"response_time"`
	ResponseHeaders     string `json:"response_headers"`
	ResponsePayload     string `json:"response_payload"`
	ResponseRemark      string `json:"response_remark"`
	ResponseCode        string `json:"response_code"`
	HTTPStatusCode      string `json:"http_status_code"`
	OrderID             string `json:"order_id"`
	ProvinceCode        string `json:"province_code"`
	CityCode            string `json:"city_code"`
	TotalTime           int64  `json:"total_time"`
	ErrorCode           string `json:"error_code"`
	RequestIP           string `json:"request_ip"`
	HostIP              string `json:"host_ip"`
	Hostname            string `json:"hostname"`
	AccountType         string `json:"account_type"`
	AccountNum          string `json:"account_num"`
	ResponseAccountType string `json:"response_account_type"`
	ResponseAccountNum  string `json:"response_account_num"`
	User                string `json:"user"`
	Tag                 string `json:"tag"`
	ServiceLine         string `json:"service_line"`
	// contains filtered or unexported fields
}

func (*TransactionLog) GetAccount added in v0.2.0

func (log *TransactionLog) GetAccount() *TransactionLog

func (*TransactionLog) GetAddress added in v0.2.0

func (log *TransactionLog) GetAddress() *TransactionLog

func (*TransactionLog) GetAppName added in v0.2.0

func (log *TransactionLog) GetAppName() *TransactionLog

func (*TransactionLog) GetDialogType added in v0.2.0

func (log *TransactionLog) GetDialogType() *TransactionLog

func (*TransactionLog) GetErrorCode added in v0.2.0

func (log *TransactionLog) GetErrorCode() *TransactionLog

func (*TransactionLog) GetFCode added in v0.2.0

func (log *TransactionLog) GetFCode() *TransactionLog

func (*TransactionLog) GetHTTPMethod added in v0.2.0

func (log *TransactionLog) GetHTTPMethod() *TransactionLog

func (*TransactionLog) GetHTTPStatusCode added in v0.2.0

func (log *TransactionLog) GetHTTPStatusCode() *TransactionLog

func (*TransactionLog) GetHostIP added in v0.2.0

func (log *TransactionLog) GetHostIP() *TransactionLog

func (*TransactionLog) GetHostname added in v0.2.0

func (log *TransactionLog) GetHostname() *TransactionLog

func (*TransactionLog) GetLevel added in v0.2.0

func (log *TransactionLog) GetLevel() *TransactionLog

func (*TransactionLog) GetLogTime added in v0.2.0

func (log *TransactionLog) GetLogTime() *TransactionLog

func (*TransactionLog) GetLogger added in v0.2.0

func (log *TransactionLog) GetLogger() *TransactionLog

func (*TransactionLog) GetMethodCode added in v0.2.0

func (log *TransactionLog) GetMethodCode() *TransactionLog

func (*TransactionLog) GetMethodName added in v0.2.0

func (log *TransactionLog) GetMethodName() *TransactionLog

func (*TransactionLog) GetOrderID added in v0.2.0

func (log *TransactionLog) GetOrderID() *TransactionLog

func (*TransactionLog) GetProvinceCodeAndCityCode added in v0.2.0

func (log *TransactionLog) GetProvinceCodeAndCityCode() *TransactionLog

func (*TransactionLog) GetRequestHeaders added in v0.2.0

func (log *TransactionLog) GetRequestHeaders() *TransactionLog

func (*TransactionLog) GetRequestIP added in v0.2.0

func (log *TransactionLog) GetRequestIP() *TransactionLog

func (*TransactionLog) GetRequestPayload added in v0.2.0

func (log *TransactionLog) GetRequestPayload() *TransactionLog

GetRequestPayload 获取请求数据,仅获取查询参数,表单数据,JSON数据。

func (*TransactionLog) GetRequestTime added in v0.2.0

func (log *TransactionLog) GetRequestTime() *TransactionLog

func (*TransactionLog) GetResponseAccount added in v0.2.0

func (log *TransactionLog) GetResponseAccount() *TransactionLog

func (*TransactionLog) GetResponseCode added in v0.2.0

func (log *TransactionLog) GetResponseCode() *TransactionLog

func (*TransactionLog) GetResponseHeaders added in v0.2.0

func (log *TransactionLog) GetResponseHeaders() *TransactionLog

func (*TransactionLog) GetResponsePayload added in v0.2.0

func (log *TransactionLog) GetResponsePayload() *TransactionLog

func (*TransactionLog) GetResponseRemark added in v0.2.0

func (log *TransactionLog) GetResponseRemark() *TransactionLog

func (*TransactionLog) GetResponseTime added in v0.2.0

func (log *TransactionLog) GetResponseTime() *TransactionLog

func (*TransactionLog) GetServiceLine added in v0.2.0

func (log *TransactionLog) GetServiceLine() *TransactionLog

func (*TransactionLog) GetTCode added in v0.2.0

func (log *TransactionLog) GetTCode() *TransactionLog

func (*TransactionLog) GetTag added in v0.2.0

func (log *TransactionLog) GetTag() *TransactionLog

func (*TransactionLog) GetThread added in v0.2.0

func (log *TransactionLog) GetThread() *TransactionLog

GetThread 获取当前线程ID(这里实际获取的是 Goroutine ID)。

func (*TransactionLog) GetTotalTime added in v0.2.0

func (log *TransactionLog) GetTotalTime() *TransactionLog

func (*TransactionLog) GetTransactionID added in v0.2.0

func (log *TransactionLog) GetTransactionID() *TransactionLog

func (*TransactionLog) GetUser added in v0.2.0

func (log *TransactionLog) GetUser() *TransactionLog

Directories

Path Synopsis

Jump to

Keyboard shortcuts

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