feat(core): 初始化基础框架并完善接入文档
Verify / verify (push) Canceled after 0s

抽取 Gin、配置、日志、数据库、Redis 与出站 HTTP 基础能力。
新增统一接入指南,将能力清单和相对链接检查纳入 make verify。
对齐远端 module 路径,修正 Redis 读写超时特殊值映射。

验证:make verify、make race-check 均通过。
This commit is contained in:
zhangdeman committed 2026-11-26 19:50:52 -08:00
commit b4c3ac622c
55 files changed
+5862

No files matched your search

+200
View File
@@ -0,0 +1,200 @@
package http
import (
"context"
"errors"
"net"
"net/http"
"sort"
"sync"
"time"
"git.zhangdeman.cn/github/ginframework/diagnostic"
"git.zhangdeman.cn/github/ginframework/fault"
failure "git.zhangdeman.cn/github/ginframework/internal/failure"
"git.zhangdeman.cn/github/ginframework/logger"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"go.uber.org/zap"
)
const (
startKey = "ginframework:start"
)
// Config 是 HTTP 服务的数据配置,实例之间不共享响应协议设置。
type Config struct {
Service string `json:"service" yaml:"service" dc:"诊断中的服务名称"`
SuccessCode int `json:"success_code" yaml:"success_code" dc:"成功业务码,零为默认"`
ReadHeaderTimeoutMS int `json:"read_header_timeout_ms" yaml:"read_header_timeout_ms" dc:"请求头读取超时毫秒,缺省 5000"`
TrustedProxies []string `json:"trusted_proxies" yaml:"trusted_proxies" dc:"可信代理名单,缺省不信任转发头"`
}
// Options 是调用方显式注入的 HTTP 运行依赖。
type Options struct {
TrustedFields map[string]TrustedField `json:"-" dc:"按 Go 字段名覆盖可信公共参数的启动配置"`
Middleware []gin.HandlerFunc `json:"-" dc:"业务认证等全局中间件,启动时复制"`
ErrorMapper ErrorMapper `json:"-" dc:"业务错误到公开响应的转换函数"`
AccessLogger *zap.Logger `json:"-" dc:"访问日志实例,nil 表示关闭"`
}
// Server 拥有单个 Gin 引擎及 HTTP 生命周期,不拥有数据库和业务协程。
type Server struct {
config Config `dc:"构造时复制的数据配置"`
options Options `dc:"显式注入的运行依赖"`
engine *gin.Engine `dc:"仅在注册阶段修改的原生 Gin 引擎"`
lock sync.Mutex `dc:"协调路由冻结、监听和停止接收"`
frozen bool `dc:"开始处理请求后禁止注册"`
stopping bool `dc:"退出期间拒绝新请求"`
served bool `dc:"禁止重复启动监听"`
server *http.Server `dc:"当前服务的原生 HTTP 实例"`
requests sync.WaitGroup `dc:"等待已接受请求全部退出"`
root context.Context `dc:"服务拥有的取消上下文"`
cancel context.CancelFunc `dc:"取消长请求及 SSE 的函数"`
routes []route `dc:"启动期保存的不可变路由计划"`
trustedFieldNames []string `dc:"启动时排序的可信字段名,避免每个请求重复构建和排序"`
}
// NewServer 创建独立 HTTP 实例,不修改 Gin 全局运行模式。
// 入参:cfg 为数据配置,options 为运行期函数及日志依赖。
// 返回:服务实例;非法代理和超时配置返回内部错误。
func NewServer(cfg Config, options Options) (*Server, error) {
if cfg.ReadHeaderTimeoutMS < 0 {
return nil, failure.Wrap(codeServerConfig, "validate HTTP timeout failed", errors.New("negative header timeout"))
}
if cfg.ReadHeaderTimeoutMS == 0 {
cfg.ReadHeaderTimeoutMS = 5000
}
cfg.TrustedProxies = append([]string(nil), cfg.TrustedProxies...)
options.Middleware = append([]gin.HandlerFunc(nil), options.Middleware...)
if len(options.Middleware) > 58 {
return nil, failure.Wrap(codeMiddlewareCount, "validate HTTP middleware count failed", errors.New("too many global middleware handlers"))
}
for _, handler := range options.Middleware {
if handler == nil {
return nil, failure.Wrap(codeMiddlewareHandler, "validate HTTP middleware failed", errors.New("nil global middleware"))
}
}
trusted := make(map[string]TrustedField, len(options.TrustedFields))
for name, reader := range options.TrustedFields {
if name == "" || reader == nil {
return nil, failure.Wrap(codeTrustedRule, "validate trusted field rule failed", errors.New("trusted field name and callback are required"))
}
trusted[name] = reader
}
options.TrustedFields = trusted
root, cancel := context.WithCancel(context.Background())
s := &Server{config: cfg, options: options, root: root, cancel: cancel}
for name := range trusted {
s.trustedFieldNames = append(s.trustedFieldNames, name)
}
sort.Strings(s.trustedFieldNames)
engine, err := s.buildEngine(nil)
if err != nil {
cancel()
return nil, err
}
s.engine = engine
return s, nil
}
// Handler 冻结路由并返回可用于 httptest 或原生 HTTP 的处理器。
// 返回:管理在途请求计数的处理器,退出期间拒绝新请求。
func (s *Server) Handler() http.Handler {
s.lock.Lock()
s.frozen = true
s.lock.Unlock()
return http.HandlerFunc(s.serveRequest)
}
// serveRequest 协调请求接收、取消和完成计数。
// 入参:writer 为响应写入器,request 为原始请求。
func (s *Server) serveRequest(writer http.ResponseWriter, request *http.Request) {
s.lock.Lock()
if s.stopping {
s.lock.Unlock()
http.Error(writer, "Service Unavailable", http.StatusServiceUnavailable)
return
}
s.requests.Add(1)
s.lock.Unlock()
defer s.requests.Done()
ctx, cancel := context.WithCancel(request.Context())
stop := context.AfterFunc(s.root, cancel)
defer func() { stop(); cancel() }()
s.engine.ServeHTTP(writer, request.WithContext(ctx))
}
// Serve 使用调用方监听器提供服务,一次启动后不允许重启。
// 入参:listener 为当前实例接管的网络监听器。
// 返回:正常关闭返回 nil,其余监听错误保留原因链。
func (s *Server) Serve(listener net.Listener) error {
s.lock.Lock()
if s.served || s.stopping {
s.lock.Unlock()
return failure.Wrap(codeLifecycle, "start HTTP lifecycle failed", errors.New("server cannot be started again"))
}
s.frozen = true
handler := http.HandlerFunc(s.serveRequest)
s.served = true
s.server = &http.Server{Handler: handler, ReadHeaderTimeout: time.Duration(s.config.ReadHeaderTimeoutMS) * time.Millisecond}
server := s.server
s.lock.Unlock()
err := server.Serve(listener)
if errors.Is(err, http.ErrServerClosed) {
return nil
}
return failure.Wrap(codeServe, "serve HTTP requests failed", err)
}
// Shutdown 停止接收并取消请求,等待所有已接受 Handler 退出。
// 入参:ctx 为网络排空时限;超时后强制关闭网络连接,仍等待业务 Handler 返回。
// 返回:网络关闭或超时错误;返回前不再有 Handler 使用应用资源。
// 隐式逻辑:Handler 必须响应 Context 取消,否则本方法会继续等待,不提前释放数据库。
func (s *Server) Shutdown(ctx context.Context) error {
s.lock.Lock()
s.stopping = true
s.frozen = true
server := s.server
s.cancel()
s.lock.Unlock()
var (
err error
)
if server != nil {
err = server.Shutdown(ctx)
if err != nil {
err = errors.Join(err, server.Close())
}
}
s.requests.Wait()
return failure.Wrap(codeShutdown, "drain HTTP server failed", err)
}
// initialize 生成可信请求诊断并在请求结束时输出安全的访问元数据。
// 入参:ctx 为当前 Gin 请求上下文。
func (s *Server) initialize(ctx *gin.Context) {
start := time.Now()
ctx.Set(startKey, start)
id := uuid.NewString()
ctx.Request = ctx.Request.WithContext(diagnostic.With(ctx.Request.Context(), diagnostic.Snapshot{RequestID: id, TraceID: id, URI: ctx.Request.URL.Path, Method: ctx.Request.Method, Service: s.config.Service}))
ctx.Header("X-Request-ID", id)
defer func() {
if recovered := recover(); recovered != nil {
// panic 值可能含凭据,不写入响应或日志。
panicError := fault.New(codePanic, "recover HTTP handler panic", nil)
logger.RecordErrorContext(ctx.Request.Context(), "recover HTTP handler panic", panicError)
s.writeResult(ctx, nil, panicError, http.StatusInternalServerError)
ctx.Abort()
}
if ctx.Request.MultipartForm != nil {
if err := ctx.Request.MultipartForm.RemoveAll(); err != nil {
logger.RecordErrorContext(ctx.Request.Context(), "remove multipart temporary files failed", fault.New(codeMultipartCleanup, "remove multipart temporary files failed", err))
}
}
if s.options.AccessLogger != nil {
s.options.AccessLogger.Info("HTTP request completed", zap.String("trace_id", id), zap.String("uri", ctx.Request.URL.Path), zap.String("method", ctx.Request.Method), zap.Int("status", ctx.Writer.Status()), zap.Duration("duration", time.Since(start)))
}
}()
ctx.Next()
}
Reference in new issue
Block a user
Blocking a user prevents them from interacting with repositories, such as opening or commenting on pull requests or issues. Learn more about blocking a user.