golang之http封装

go让日志显示行数

log.SetFlags(log.Lshortfile | log.LstdFlags)

一个简单的golang http封装

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
func HttpGetCall(url string, params map[string]string, cooikes []*http.Cookie, res interface{}) error {
op := NewRequestOptions()
op.Params = params
op.Cookies = cooikes
resp, err := grequests.Get(url, op)
if err != nil {
return err
}

if !resp.Ok {
return fmt.Errorf("Response failed with status code: %d.", resp.StatusCode)
}

if res != nil {
return resp.JSON(res)
}
return nil
}
1
2
3
4
5
6
7
8
func NewRequestOptions() *grequests.RequestOptions {
return &grequests.RequestOptions{
DialTimeout: 5 * time.Second,
TLSHandshakeTimeout: 5 * time.Second,
RequestTimeout: 5 * time.Second,
InsecureSkipVerify: true,
}
}

返回类型的结构体

1
2
3
4
5
type Message struct {
Code int `json:"code"`
Msg string `json:"msg"`
Data *json.RawMessage `json:"data"` // must be *json.RawMessage
}

调用例子:

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
func GetUserInfoByAccount(account string) (*protocol.UserCenterFilterUserInfo, int) {
params := map[string]string{
"field": "member_name",
"value": account,
}

var m protocol.Message
url := getUserCenterInnerDomain() + "/get_filter_user_and_company_list"
err := util.HttpGetCall(url, params, nil, &m)
if err != nil {
logger.Warnning("GetUserInfoByAccount error:", err.Error())
return nil, protocol.CODE_SYSTEM_ERROR
}

type Resp struct {
Infos []protocol.UserCenterFilterUserInfo `json:"infos"`
}

var resp Resp

if err = json.Unmarshal(*m.Data, &resp); err != nil {
logger.Warnning("GetUserInfoByAccount error:", err.Error())
return nil, protocol.CODE_SYSTEM_ERROR
}

if util.IsDebug() {
logger.Debug(resp)
}

if m.Code != protocol.CODE_OK {
log.Printf("request filed:code=%d msg=%s\n", m.Code, m.Msg)
return nil, protocol.CODE_SYSTEM_ERROR
}
if len(resp.Infos) == 0 {
return nil, protocol.CODE_USER_NOT_EXIST
}
return &resp.Infos[0], protocol.CODE_OK

}
感谢你的打赏哦!