-
Notifications
You must be signed in to change notification settings - Fork 3
/
app.go
93 lines (84 loc) · 1.99 KB
/
app.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
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
package pintoto
import (
"encoding/json"
"errors"
"fmt"
"github.com/go-redis/redis/v8"
"go.mongodb.org/mongo-driver/mongo"
"go.uber.org/zap"
"gorm.io/gorm"
"io/ioutil"
"math"
"net/http"
"strconv"
"strings"
"time"
)
// App 电影票服务
type App struct {
AppKey string
AppSecret string
ZapLog *zap.Logger // 日志服务
Db *gorm.DB // 关系数据库服务
RDb *redis.Client // 缓存数据库服务
MDb *mongo.Client // 非关系数据库服务
}
type ErrResp struct {
Success bool `json:"success"`
Message string `json:"message"`
Data interface{} `json:"data"`
Code int `json:"code"`
}
func (app *App) request(url string, params map[string]interface{}) ([]byte, error) {
// 公共参数
params["time"] = time.Now().Unix()
params["appKey"] = app.AppKey
// 签名
params["sign"] = app.getSign(app.AppSecret, params)
var req *http.Request
req, err := http.NewRequest("POST", url, strings.NewReader(app.getRequestData(params)))
if err != nil {
return nil, err
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
httpClient := &http.Client{}
var response *http.Response
response, err = httpClient.Do(req)
if err != nil {
return nil, nil
}
// 请求错误
if response.StatusCode != 200 {
return nil, errors.New(fmt.Sprintf("请求错误:%d", response.StatusCode))
}
defer response.Body.Close()
body, err := ioutil.ReadAll(response.Body)
// 日志
if app.ZapLog != nil {
app.ZapLog.Sugar().Info(fmt.Sprintf("%s %s", url, body))
}
// 检查错误
apiErr := ErrResp{}
err = json.Unmarshal(body, &apiErr)
if err != nil {
return nil, err
}
// 接口状态错误
if apiErr.Code != 200 {
return nil, errors.New(apiErr.Message)
}
return body, nil
}
func (app *App) GradeToFloat64(i interface{}) float64 {
switch v := i.(type) {
case string:
float, _ := strconv.ParseFloat(v, 64)
return float
case float64:
return v
case int64:
return float64(v) / math.Pow10(0)
default:
return 0
}
}