-
Notifications
You must be signed in to change notification settings - Fork 15
/
response.go
46 lines (40 loc) · 925 Bytes
/
response.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
package opentaobao
import (
"encoding/json"
"errors"
"fmt"
"net/http"
)
func RespDecode(httpResp *http.Response, v any) error {
resp := &Response{
Data: v,
}
err := json.NewDecoder(httpResp.Body).Decode(resp)
if err != nil {
return err
}
fmt.Printf("resp: %+v\n", resp)
fmt.Printf("resp.Data: %+v\n", resp.Data)
if resp.IsError() {
return resp.Error()
}
if httpResp.StatusCode != http.StatusOK {
return fmt.Errorf("http status code: %d", httpResp.StatusCode)
}
return nil
}
// Error HTTP响应错误项
type Error struct {
Code int `json:"code" swaggo:"true,错误码"`
Message string `json:"message" swaggo:"true,错误信息"`
}
type Response struct {
Err Error `json:"error" swaggo:"true,错误项"`
Data any `json:"data"`
}
func (e *Response) IsError() bool {
return e.Err.Code != 200 && e.Err.Code != 0
}
func (e *Response) Error() error {
return errors.New(e.Err.Message)
}