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 · 12 天前 · 1614 次点击

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

    7 条回复    2025-06-10 11:08:38 +08:00
    lrh3321
        2
    lrh3321  
       12 天前
    https://pkg.go.dev/resty.dev/v3#Request.SetError 可以在错误码大于 399 的时候,用别的结构体来反序列化
    Maboroshii
        3
    Maboroshii  
       11 天前 via Android
    json.rawmessage, 自己写吧
    vincentWdp
        4
    vincentWdp  
       11 天前
    自己写啊.
    neoblackcap
        5
    neoblackcap  
       11 天前
    到底返回的内容是不是合法的 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  
       11 天前
    错误码非 200 ,返回的很可能不是 json 。太细化的通用性不强。自己写一个几十行代码的事。
    hzzhzzdogee
        7
    hzzhzzdogee  
       11 天前
    不想手写就 resty 吧, 赞同楼上
    关于   ·   帮助文档   ·   博客   ·   API   ·   FAQ   ·   实用小工具   ·   2707 人在线   最高记录 6679   ·     Select Language
    创意工作者们的社区
    World is powered by solitude
    VERSION: 3.9.8.5 · 20ms · UTC 04:08 · PVG 12:08 · LAX 21:08 · JFK 00:08
    Developed with CodeLauncher
    ♥ Do have faith in what you're doing.