//分享一个比较字符串数字差值的函数:
// CalcBudgetDiff 计算预算差值
func CalcBudgetDiff(start, end string) (float64, error) {
s1, err := strconv.ParseFloat(start, 64)
if err != nil {
return 0.00, err
}
e1, err := strconv.ParseFloat(end, 64)
if err != nil {
return 0.00, err
}
d1 := e1 - s1
f, err := strconv.ParseFloat(fmt.Sprintf("%.2f", d1), 64)
if err != nil {
return 0.00, err
}
return f, nil
}
|
//Curl函数,phper最为熟悉
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
| // Curl 网络请求函数
// @Summary 网络请求函数
// @Description 网络请求函数
// @Tags 网络请求函数
// @Param method: GET/POST string
// @Param dataStr string k1=v1&k2=v2或者json数据,由header头决定
// @Param header map[string]string
// @Success string, nil
func Curl(method string, urls string, dataStr string, header map[string]string) ([]byte, error) {
client := &http.Client{}
req, err := http.NewRequest(method, urls, strings.NewReader(dataStr))
if err != nil {
return nil, err
}
if header != nil {
for k, v := range header {
req.Header.Set(k, v)
}
}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
if resp.Body == nil {
return nil, errors.New("resp.Body is empty")
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
if body == nil || len(body) == 0 {
return nil, errors.New("httpDo返回的body为空")
}
return body, nil
}
|
//用于打印参数:
1
2
3
4
5
6
7
| func Debug(param ...interface{}) {
fmt.Println("+++++++++++++")
for _, v := range param {
fmt.Println(fmt.Sprintf("%+v", v))
}
fmt.Println("+++++++++++++")
}
|
//跨域处理
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
| //跨域处理
func CrosHandler() gin.HandlerFunc {
return func(context *gin.Context) {
method := context.Request.Method
context.Writer.Header().Set("Access-Control-Allow-Origin", "*")
context.Header("Access-Control-Allow-Origin", "*") // 设置允许访问所有域
context.Header("Access-Control-Allow-Methods", "POST, GET, OPTIONS, PUT, DELETE,UPDATE")
context.Header("Access-Control-Allow-Headers", "Authorization, Content-Length, X-CSRF-Token, Token,session,X_Requested_With,Accept, Origin, Host, Connection, Accept-Encoding, Accept-Language,DNT, X-CustomHeader, Keep-Alive, User-Agent, X-Requested-With, If-Modified-Since, Cache-Control, Content-Type, Pragma,token,openid,opentoken")
context.Header("Access-Control-Expose-Headers", "Content-Length, Access-Control-Allow-Origin, Access-Control-Allow-Headers,Cache-Control,Content-Language,Content-Type,Expires,Last-Modified,Pragma,FooBar")
context.Header("Access-Control-Max-Age", "172800")
context.Header("Access-Control-Allow-Credentials", "false")
context.Set("content-type", "application/json") 设置返回格式是json
if method == "OPTIONS" {
context.JSON(http.StatusOK, result.Result{Code: result.OK, Data: "Options Request!"})
}
//处理请求
context.Next()
}
}
|
|