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

29 天前
 byerer

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

1964 次点击
所在节点    Go 编程语言
8 条回复
lrh3321
29 天前
lrh3321
29 天前
https://pkg.go.dev/resty.dev/v3#Request.SetError 可以在错误码大于 399 的时候,用别的结构体来反序列化
Maboroshii
29 天前
json.rawmessage, 自己写吧
vincentWdp
29 天前
自己写啊.
neoblackcap
29 天前
到底返回的内容是不是合法的 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
29 天前
错误码非 200 ,返回的很可能不是 json 。太细化的通用性不强。自己写一个几十行代码的事。
hzzhzzdogee
28 天前
不想手写就 resty 吧, 赞同楼上
guonaihong
16 天前
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

这是一个专为移动设备优化的页面(即为了让你能够在 Google 搜索结果里秒开这个页面),如果你希望参与 V2EX 社区的讨论,你可以继续到 V2EX 上打开本讨论主题的完整版本。

https://ex.noerr.eu.org/t/1137327

V2EX 是创意工作者们的社区,是一个分享自己正在做的有趣事物、交流想法,可以遇见新朋友甚至新机会的地方。

V2EX is a community of developers, designers and creative people.

© 2021 V2EX