Files
zogo/httpx/README.md
T

32 lines
1.1 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
- `wsc.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 内部校验。