如题,在"github.com/carlmjohnson/requests"包中,如果返回状态码非 200 ,则不会解析结构体,有没有可以根据状态码去选择不同结构体进行反序列化的包
![]() |
2
lrh3321 13 天前
https://pkg.go.dev/resty.dev/v3#Request.SetError 可以在错误码大于 399 的时候,用别的结构体来反序列化
|
![]() |
3
Maboroshii 13 天前 via Android
json.rawmessage, 自己写吧
|
4
vincentWdp 13 天前
自己写啊.
|
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 对象 ``` |
6
kneo 13 天前
错误码非 200 ,返回的很可能不是 json 。太细化的通用性不强。自己写一个几十行代码的事。
|
![]() |
7
hzzhzzdogee 12 天前
不想手写就 resty 吧, 赞同楼上
|
![]() |
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 |