Files
zogo/httpx/README.md
T
4566704 e1c0cc1136 feat(httpx): 并入 go-hua/httpx 的 ParseXML 并补齐单元测试
- ParseXML(XML 请求体绑定, 空请求体返回 nil)为 zogo 版本唯一缺口,
  从 go-hua/httpx 并入; 顶层 README 同步补充说明
- 移植 go-hua 全套 httpx 测试(CodeMsg/OkJson/ErrorJson/四种绑定/Validate/
  ParseXML)并新增 Handle/HandleResult/空 body 用例; 修正 README 中
  wsc.New 笔误为 New
2026-09-20 12:37:11 +08:00

43 lines
1.5 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# httpx
Gin 服务的统一出入参收口。
## 响应
统一信封 `{"code":0,"msg":"OK","data":...}`:
- `OkJson(c, data)` —— 成功出参
- `ErrorJson(c, err)` —— 错误出参;`*CodeMsg` 携带的错误码**透出**(如 401),其余错误折叠为 code 1
- `New(401, "未登录")` 构造带码错误
## Handler 收口
```go
// 泛型:Parse 取参 → 调 logic → 统一出参
httpx.Handle(c, func(req *CreateReq) (*CreateResp, error) { return svc.Create(req) })
httpx.HandleResult(c, data, err) // 非泛型场景
```
## Parse 参数绑定
`Parse(c, &req)` 按固定顺序绑定:**uri → query → header → json body**,全部绑定后统一跑
binding tag 校验(`bindingValidator`,与 gin 同源 tag 名)。
注意事项:
- 包 `init()` 会设置 `binding.Validator = nil`(关闭 gin 内置校验,避免 query 阶段误报
json 字段的 required)。**引入本包即全局生效**,服务内不要绕过 Parse 自行 ShouldBind。
- 请求结构体可实现 `Validate() error` 接口做自定义校验,在 binding 校验之前调用。
- body 解析用 `json.NewDecoder` 直解,不触发 gin 内部校验。
## ParseXML(自 go-hua/httpx 并入)
XML 报文(如第三方回调)不在 Parse 主流程内,按需显式调用:
```go
if err := httpx.ParseXML(c, &req); err != nil { ... } // 空请求体返回 nil
```
单元测试覆盖 OkJson/ErrorJson/四种绑定/Validate 失败/ParseXML/Handle/HandleResult
([httpx_test.go](httpx_test.go),自 go-hua/httpx 移植并扩充)。