The Go Programming Language
http://golang.org/
Go Playground
Go Projects
Revel Web Framework
byerer

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

  •  
  •   byerer · Jun 9, 2025 · 2767 views
    This topic created in 339 days ago, the information mentioned may be changed or developed.

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

    8 replies    2025-06-22 20:10:16 +08:00
    lrh3321
        1
    lrh3321  
       Jun 9, 2025
    lrh3321
        2
    lrh3321  
       Jun 9, 2025   ❤️ 1
    https://pkg.go.dev/resty.dev/v3#Request.SetError 可以在错误码大于 399 的时候,用别的结构体来反序列化
    Maboroshii
        3
    Maboroshii  
       Jun 9, 2025 via Android
    json.rawmessage, 自己写吧
    vincentWdp
        4
    vincentWdp  
       Jun 9, 2025
    自己写啊.
    neoblackcap
        5
    neoblackcap  
       Jun 9, 2025
    到底返回的内容是不是合法的 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  
       Jun 9, 2025
    错误码非 200 ,返回的很可能不是 json 。太细化的通用性不强。自己写一个几十行代码的事。
    hzzhzzdogee
        7
    hzzhzzdogee  
       Jun 10, 2025
    不想手写就 resty 吧, 赞同楼上
    guonaihong
        8
    guonaihong  
       Jun 22, 2025   ❤️ 1
    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
    About   ·   Help   ·   Advertise   ·   Blog   ·   API   ·   FAQ   ·   Solana   ·   945 Online   Highest 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 42ms · UTC 20:07 · PVG 04:07 · LAX 13:07 · JFK 16:07
    ♥ Do have faith in what you're doing.