httplibServiceGateway.go
1.5 KB
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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
package service_gateway
import (
"encoding/json"
"fmt"
"github.com/astaxie/beego/httplib"
"strconv"
"strings"
"time"
)
type httplibBaseServiceGateway struct {
baseURL string
connectTimeout time.Duration
readWriteTimeout time.Duration
}
func (serviceGateway *httplibBaseServiceGateway) createRequest(url string, method string) *httplib.BeegoHTTPRequest {
var request *httplib.BeegoHTTPRequest
switch method {
case "get":
request = httplib.Get(url)
break
case "post":
request = httplib.Post(url)
break
case "put":
request = httplib.Put(url)
break
case "delete":
request = httplib.Delete(url)
break
case "head":
request = httplib.Head(url)
break
default:
request = httplib.Get(url)
}
return request.SetTimeout(serviceGateway.connectTimeout, serviceGateway.readWriteTimeout)
}
func (serviceGateway *httplibBaseServiceGateway) responseHandle(response map[string]interface{}) (map[string]interface{}, error) {
data := make(map[string]interface{})
var err error
if code, ok := response["code"]; ok {
code := code.(float64)
if code == 0 {
data = response["data"].(map[string]interface{})
} else {
msg := response["msg"].(string)
err = fmt.Errorf(strings.Join([]string{strconv.FormatFloat(code, 'f', -1, 64), msg}, " "))
}
} else {
jsonBytes, marshalErr := json.Marshal(response)
if marshalErr != nil {
err = marshalErr
}
err = fmt.Errorf("无法解析的网关服务数据返回格式:%s", string(jsonBytes))
}
return data, err
}