web

package
v0.1.2 Latest Latest
Warning

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

Go to latest
Published: Oct 30, 2025 License: MIT Imports: 13 Imported by: 0

README

web - Gin 框架封装

基于 Gin 的生产级 HTTP 服务器封装,内置日志、链路追踪、指标监控支持

✨ 特性

  • 🚀 开箱即用 - 简单配置即可启动
  • 📝 自动日志 - 记录每个请求的详细信息
  • 🔍 链路追踪 - 集成 OpenTelemetry
  • 📊 指标监控 - 支持 Prometheus
  • 🛡️ 智能处理 - 自动处理大文件和大响应
  • 🔄 优雅关闭 - 支持优雅关闭服务器
  • 高性能 - 基于 Gin,性能优异

📦 安装

go get github.com/Si40Code/kit/web

🚀 快速开始

package main

import (
	"github.com/Si40Code/kit/web"
	"github.com/gin-gonic/gin"
)

func main() {
	server := web.New(
		web.WithMode(web.ReleaseMode),
		web.WithServiceName("my-service"),
	)

	engine := server.Engine()
	engine.GET("/ping", func(c *gin.Context) {
		web.Success(c, gin.H{"message": "pong"})
	})

	server.RunWithGracefulShutdown(":8080")
}

📚 示例

示例 说明
01_basic 基础用法
02_with_trace 集成链路追踪
03_with_metric 集成指标监控
04_file_upload 文件上传处理
05_custom_logger 自定义日志
06_production 生产环境配置

🔧 配置选项

基础配置
  • WithMode(mode) - 设置运行模式(Debug/Release/Test)
  • WithServiceName(name) - 设置服务名称
日志配置
  • WithLogger(logger) - 自定义日志记录器
  • WithSkipPaths(paths...) - 跳过特定路径的日志
  • WithMaxBodyLogSize(size) - 设置最大 body 日志大小
  • WithSlowRequestThreshold(duration) - 设置慢请求阈值
功能开关
  • WithTrace() - 启用链路追踪
  • WithMetric(recorder) - 启用指标监控
  • WithRecover() - 启用 panic 恢复(默认开启)
  • WithCORS() - 启用 CORS
文件上传
  • WithMaxMultipartMemory(size) - 设置最大文件上传内存

🎯 最佳实践

1. 日志处理
  • 敏感信息自动脱敏(密码、token 等)
  • 大请求/响应自动截断
  • 文件上传只记录元信息
2. 性能优化
  • 跳过健康检查等高频端点的日志
  • 合理设置 body 日志大小
  • 使用异步指标上报
3. 生产环境
server := web.New(
	web.WithMode(web.ReleaseMode),
	web.WithServiceName("prod-service"),
	web.WithLogger(yourLogger),
	web.WithTrace(),
	web.WithMetric(yourMetricRecorder),
	web.WithSkipPaths("/health", "/metrics"),
	web.WithMaxBodyLogSize(4096),
	web.WithSlowRequestThreshold(3*time.Second),
)

📝 日志格式

{
  "client_ip": "127.0.0.1",
  "method": "POST",
  "path": "/api/user",
  "query": "id=123",
  "status": 200,
  "latency_ms": 45,
  "req_body": "{\"name\":\"John\"}",
  "resp_body": "{\"code\":0,\"data\":{...}}",
  "user_agent": "Mozilla/5.0..."
}

🤝 贡献

欢迎提交 Issue 和 Pull Request!

📄 许可证

MIT License

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func Error

func Error(c *gin.Context, code int, message string)

Error 错误响应

func ErrorWithStatus

func ErrorWithStatus(c *gin.Context, httpStatus int, code int, message string)

ErrorWithStatus 带 HTTP 状态码的错误响应

func Success

func Success(c *gin.Context, data interface{})

Success 成功响应

Types

type Logger

type Logger interface {
	// Info 信息日志
	Info(ctx context.Context, msg string, fields map[string]interface{})
	// Warn 警告日志
	Warn(ctx context.Context, msg string, fields map[string]interface{})
	// Error 错误日志
	Error(ctx context.Context, msg string, fields map[string]interface{})
}

Logger 日志接口

func NewLoggerAdapter

func NewLoggerAdapter(l logger.Logger) Logger

NewLoggerAdapter 创建新的 logger 适配器

type LoggerAdapter

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

LoggerAdapter 将 kit/logger.Logger 适配到 web.Logger 接口

func (*LoggerAdapter) Error

func (a *LoggerAdapter) Error(ctx context.Context, msg string, fields map[string]interface{})

Error 记录 error 级别日志

func (*LoggerAdapter) Info

func (a *LoggerAdapter) Info(ctx context.Context, msg string, fields map[string]interface{})

Info 记录 info 级别日志

func (*LoggerAdapter) Warn

func (a *LoggerAdapter) Warn(ctx context.Context, msg string, fields map[string]interface{})

Warn 记录 warn 级别日志

type MetricData

type MetricData struct {
	Method   string
	Path     string
	Status   int
	Duration time.Duration
}

MetricData 指标数据

type MetricRecorder

type MetricRecorder interface {
	// RecordRequest 记录请求指标
	RecordRequest(data MetricData)
}

MetricRecorder 指标记录器接口

type Mode

type Mode string

Mode 运行模式

const (
	DebugMode   Mode = "debug"
	ReleaseMode Mode = "release"
	TestMode    Mode = "test"
)

type Option

type Option func(*options)

Option 配置选项

func WithCORS

func WithCORS() Option

WithCORS 启用 CORS

func WithLogger

func WithLogger(logger Logger) Option

WithLogger 设置日志记录器

func WithMaxBodyLogSize

func WithMaxBodyLogSize(size int64) Option

WithMaxBodyLogSize 设置最大 body 日志大小

func WithMaxMultipartMemory

func WithMaxMultipartMemory(size int64) Option

WithMaxMultipartMemory 设置最大文件上传内存

func WithMetric

func WithMetric(recorder MetricRecorder) Option

WithMetric 启用指标监控

func WithMiddleware

func WithMiddleware(middlewares ...gin.HandlerFunc) Option

WithMiddleware 添加自定义中间件

func WithMode

func WithMode(mode Mode) Option

WithMode 设置运行模式

func WithPrettyJSON

func WithPrettyJSON() Option

WithPrettyJSON 启用格式化 JSON 响应

func WithRecover

func WithRecover() Option

WithRecover 启用 panic 恢复

func WithServiceName

func WithServiceName(name string) Option

WithServiceName 设置服务名称

func WithSkipPaths

func WithSkipPaths(paths ...string) Option

WithSkipPaths 设置跳过日志记录的路径

func WithSlowRequestThreshold

func WithSlowRequestThreshold(duration time.Duration) Option

WithSlowRequestThreshold 设置慢请求阈值

func WithTrace

func WithTrace() Option

WithTrace 启用链路追踪

type Response

type Response struct {
	Code    int         `json:"code"`
	Message string      `json:"message"`
	Data    interface{} `json:"data,omitempty"`
}

Response 统一响应结构

type Server

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

Server Gin 服务器封装

func New

func New(opts ...Option) *Server

New 创建一个新的 Gin 服务器

func (*Server) Engine

func (s *Server) Engine() *gin.Engine

Engine 返回底层的 Gin Engine,用于注册路由

func (*Server) Run

func (s *Server) Run(addr string) error

Run 启动服务器

func (*Server) RunWithGracefulShutdown

func (s *Server) RunWithGracefulShutdown(addr string) error

RunWithGracefulShutdown 启动服务器并支持优雅关闭

func (*Server) Shutdown

func (s *Server) Shutdown(ctx context.Context) error

Shutdown 优雅关闭服务器

Directories

Path Synopsis
examples
01_basic command
02_with_trace command
03_with_metric command
04_file_upload command
06_production command
07_with_signoz command

Jump to

Keyboard shortcuts

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