// Package webhttp 被控 HTTP 能力的极薄适配层。 // // file/shell/process 三个被控能力包统一以标准库 http.HandlerFunc 为 handler // 形态、以 Router 接口收拢路由注册, 不再绑死任何 Web 框架。消费方按自身 // 技术栈适配: 纯标准库用 ServeMuxRouter 直挂 *http.ServeMux(Go 1.22+ 方法 // +路径模式); 已有 gin 栈的用 gin.WrapH 桥接, 中间件链照常生效。 // // 由此 gin(连带其拖入的 quic-go/http3、mongo bson、ugorji codec、goccy // 等重依赖)从被控端二进制中整体消失, 体积近乎减半。 package webhttp import ( "encoding/json" "net/http" ) // Router file/shell/process 声明路由用的最小接口(pattern 形如 // "/file/list", 不含组前缀; 前缀由适配器拼)。 type Router interface { GET(pattern string, h http.HandlerFunc) POST(pattern string, h http.HandlerFunc) PUT(pattern string, h http.HandlerFunc) DELETE(pattern string, h http.HandlerFunc) HEAD(pattern string, h http.HandlerFunc) } // ServeMuxRouter 把 *http.ServeMux 适配为 Router, 注册 // "METHOD prefix+pattern" 模式路由(如 "GET /api/file/list")。 // 注册了 GET 的路径自动兼容 HEAD。 func ServeMuxRouter(mux *http.ServeMux, prefix string) Router { return &muxRouter{mux: mux, prefix: prefix} } type muxRouter struct { mux *http.ServeMux prefix string } func (m *muxRouter) route(method, pattern string) string { return method + " " + m.prefix + pattern } func (m *muxRouter) GET(pattern string, h http.HandlerFunc) { m.mux.HandleFunc(m.route(http.MethodGet, pattern), h) } func (m *muxRouter) POST(pattern string, h http.HandlerFunc) { m.mux.HandleFunc(m.route(http.MethodPost, pattern), h) } func (m *muxRouter) PUT(pattern string, h http.HandlerFunc) { m.mux.HandleFunc(m.route(http.MethodPut, pattern), h) } func (m *muxRouter) DELETE(pattern string, h http.HandlerFunc) { m.mux.HandleFunc(m.route(http.MethodDelete, pattern), h) } func (m *muxRouter) HEAD(pattern string, h http.HandlerFunc) { m.mux.HandleFunc(m.route(http.MethodHead, pattern), h) } // WriteJSON 统一 JSON 响应(响应头口径与原 gin c.JSON 一致)。 // 业务码仍在 body 的 code 字段, HTTP 状态恒 200, 与既有前端约定不变。 func WriteJSON(w http.ResponseWriter, status int, v any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) _ = json.NewEncoder(w).Encode(v) }