V2EX = way to explore
V2EX 是一个关于分享和探索的地方
现在注册
已注册用户请  登录
The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
byerer
V2EX  ›  Go 编程语言

golang 有没有可以根据不同 http 状态码,解析 json 到不同结构体的包

  •  
  •   byerer · 13 天前 · 1644 次点击

    如题,在"github.com/carlmjohnson/requests"包中,如果返回状态码非 200 ,则不会解析结构体,有没有可以根据状态码去选择不同结构体进行反序列化的包

    8 条回复    2025-06-22 20:10:16 +08:00
    lrh3321
        2
    lrh3321  
       13 天前
    https://pkg.go.dev/resty.dev/v3#Request.SetError 可以在错误码大于 399 的时候,用别的结构体来反序列化
    Maboroshii
        3
    Maboroshii  
       13 天前 via Android
    json.rawmessage, 自己写吧
    vincentWdp
        4
    vincentWdp  
       13 天前
    自己写啊.
    neoblackcap
        5
    neoblackcap  
       13 天前
    到底返回的内容是不是合法的 JSON 内容,我一般都是使用泛型结构体来实现类似的需求
    ```go
    type APIResponse[T any] struct {
    Status int `json:"status"`
    Data T `json:"data"`
    }

    func NewAPIResponse[T any](dest T) APIResponse[T] {
    return APIResponse[T]{Data: dest}
    }

    这样就可以比较方便创建不一样的 response 对象

    ```
    kneo
        6
    kneo  
       13 天前
    错误码非 200 ,返回的很可能不是 json 。太细化的通用性不强。自己写一个几十行代码的事。
    hzzhzzdogee
        7
    hzzhzzdogee  
       12 天前
    不想手写就 resty 吧, 赞同楼上
    guonaihong
        8
    guonaihong  
       7 小时 2 分钟前
    https://github.com/guonaihong/gout

    使用 callback 这个函数,可以根据 code 选择。
    用法大约是这样的。
    ```go
    func main() {

    r, str404 := Result{}, ""
    code := 0

    err := gout.GET(":8080").Callback(func(c *gout.Context) (err error) {

    switch c.Code {
    case 200: //http code 为 200 时,服务端返回的是 json 结构
    c.BindJSON(&r)
    case 404: //http code 为 404 时,服务端返回是 html 字符串
    c.BindBody(&str404)
    }
    code = c.Code
    return nil

    }).Do()

    if err != nil {
    fmt.Printf("err = %s\n", err)
    return
    }

    fmt.Printf("http code = %d, str404(%s) or json result(%v)\n", code, str404, r)

    }
    ```
    https://github.com/guonaihong/gout?tab=readme-ov-file#callback
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   906 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 23ms · UTC 19:12 · PVG 03:12 · LAX 12:12 · JFK 15:12
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.