package httpx import ( "bytes" "encoding/json" "errors" "io" "net/http" "unicode/utf8" "golang.org/x/text/encoding/simplifiedchinese" ) // 业务错误码。HTTP 状态码只表达协议层语义,业务语义走 code 字段。 const ( CodeOK = "OK" CodeInvalidParam = "INVALID_PARAM" CodeUnauthorized = "UNAUTHORIZED" CodeForbidden = "FORBIDDEN" CodeNotFound = "NOT_FOUND" CodeConflict = "CONFLICT" CodeRateLimited = "RATE_LIMITED" CodeInternal = "INTERNAL" ) // APIError 是唯一允许跨层传递的业务错误类型 type APIError struct { Status int Code string Message string Details any } func (e *APIError) Error() string { return e.Code + ": " + e.Message } func NewError(status int, code, msg string) *APIError { return &APIError{Status: status, Code: code, Message: msg} } var ( ErrUnauthorized = NewError(http.StatusUnauthorized, CodeUnauthorized, "未登录或登录已过期") ErrForbidden = NewError(http.StatusForbidden, CodeForbidden, "无权访问") ErrNotFound = NewError(http.StatusNotFound, CodeNotFound, "资源不存在") ) func InvalidParam(msg string) *APIError { return NewError(http.StatusBadRequest, CodeInvalidParam, msg) } func NotFound(msg string) *APIError { return NewError(http.StatusNotFound, CodeNotFound, msg) } func Conflict(msg string) *APIError { return NewError(http.StatusConflict, CodeConflict, msg) } // envelope 统一响应外壳,与现有 Node 版契约保持一致: // {"code":200,"message":"...","data":{...}} type envelope struct { Code any `json:"code"` Message string `json:"message,omitempty"` Data any `json:"data,omitempty"` } type errEnvelope struct { Error struct { Code string `json:"code"` Message string `json:"message"` Details any `json:"details,omitempty"` } `json:"error"` } // WriteJSON 写出成功响应。SetEscapeHTML(false) 保证中文不被转成 \uXXXX。 func WriteJSON(w http.ResponseWriter, status int, data any) { w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(status) enc := json.NewEncoder(w) enc.SetEscapeHTML(false) _ = enc.Encode(envelope{Code: 200, Data: data}) } func WriteCreated(w http.ResponseWriter, data any) { WriteJSON(w, http.StatusCreated, data) } // WriteError 把任意 error 映射成统一错误响应 func WriteError(w http.ResponseWriter, err error) { var apiErr *APIError if !errors.As(err, &apiErr) { apiErr = NewError(http.StatusInternalServerError, CodeInternal, "服务内部错误") } var body errEnvelope body.Error.Code = apiErr.Code body.Error.Message = apiErr.Message body.Error.Details = apiErr.Details w.Header().Set("Content-Type", "application/json; charset=utf-8") w.WriteHeader(apiErr.Status) enc := json.NewEncoder(w) enc.SetEscapeHTML(false) _ = enc.Encode(body) } // Decode 解析请求体,限制 1MB 防内存打爆 func Decode(r *http.Request, dst any) error { r.Body = http.MaxBytesReader(nil, r.Body, 1<<20) raw, err := io.ReadAll(r.Body) if err != nil { return InvalidParam("读取请求体失败: " + err.Error()) } if !utf8.Valid(raw) { // 自动兼容 Windows 终端/老旧客户端默认 GBK 提交的中文字符 decoded, err := simplifiedchinese.GBK.NewDecoder().Bytes(raw) if err == nil && utf8.Valid(decoded) { raw = decoded } else { return InvalidParam("请求体编码非法,必须为 UTF-8 编码") } } dec := json.NewDecoder(bytes.NewReader(raw)) dec.DisallowUnknownFields() if err := dec.Decode(dst); err != nil { return InvalidParam("请求体格式错误: " + err.Error()) } return nil }