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
This commit is contained in:
2026-09-20 12:37:11 +08:00
parent 96c63fb153
commit e1c0cc1136
4 changed files with 309 additions and 1 deletions
+54
View File
@@ -0,0 +1,54 @@
// httpx 包示例:gin 统一响应(OkJson/ErrorJson)、参数绑定(Parse)与业务校验(Validator)
package main
import (
"fmt"
"net/http"
"git.zeroonesoft.cn/golib/zogo/httpx"
"github.com/gin-gonic/gin"
)
// LoginReq 登录请求:Parse 会依次绑定 URI / Query / Header / JSON Body
type LoginReq struct {
Username string `json:"username" form:"username" uri:"username" header:"X-Username"`
Password string `json:"password" form:"password" uri:"password"`
}
// Validate 实现 httpx.Validator 接口,Parse 绑定完成后自动调用
func (r *LoginReq) Validate() error {
if r.Username == "" {
return httpx.New(1001, "用户名不能为空")
}
if r.Password == "" {
return httpx.New(1002, "密码不能为空")
}
return nil
}
func main() {
gin.SetMode(gin.ReleaseMode)
r := gin.New()
// POST /login/:username?password=xxx 或 POST /login/:username + JSON Body
r.POST("/login/:username", func(c *gin.Context) {
req := &LoginReq{}
if err := httpx.Parse(c, req); err != nil {
httpx.ErrorJson(c, err)
return
}
httpx.OkJson(c, gin.H{"welcome": req.Username})
})
r.GET("/ping", func(c *gin.Context) {
httpx.OkJson(c, "pong")
})
fmt.Println("服务已启动: http://127.0.0.1:8080")
fmt.Println("测试: curl -X POST \"http://127.0.0.1:8080/login/admin?password=123456\"")
fmt.Println("测试: curl -X POST http://127.0.0.1:8080/login/guest -d '{\"username\":\"\",\"password\":\"\"}'")
if err := http.ListenAndServe("127.0.0.1:8080", r); err != nil {
fmt.Println("服务退出:", err)
}
}