146 lines
2.5 KiB
Go
146 lines
2.5 KiB
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"crypto/sha1"
|
|
"encoding/base64"
|
|
"encoding/hex"
|
|
"io"
|
|
"io/ioutil"
|
|
"net/http"
|
|
"sort"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
// 调用POST请求
|
|
func HttpPost(url string, body string) (remoteResponse string, err error) {
|
|
|
|
bodyReader := strings.NewReader(body)
|
|
//application/x-www-form-urlencoded
|
|
//application/json
|
|
_, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
|
|
client := &http.Client{
|
|
Timeout: time.Second * 20, // 设置客户端超时为5秒
|
|
}
|
|
|
|
response, err1 := client.Post(url, "application/x-www-form-urlencoded", bodyReader)
|
|
|
|
if err1 != nil {
|
|
err = err1
|
|
return
|
|
}
|
|
defer response.Body.Close()
|
|
|
|
resBody, err2 := ioutil.ReadAll(response.Body)
|
|
|
|
if err2 != nil {
|
|
err = err2
|
|
return
|
|
}
|
|
|
|
remoteResponse = string(resBody)
|
|
|
|
return
|
|
}
|
|
|
|
// 调用Get请求
|
|
func HttpGet(url string) (remoteResponse string, err error) {
|
|
|
|
response, err1 := http.Get(url)
|
|
|
|
if err1 != nil {
|
|
err = err1
|
|
return
|
|
}
|
|
defer response.Body.Close()
|
|
|
|
resBody, err2 := ioutil.ReadAll(response.Body)
|
|
|
|
if err2 != nil {
|
|
err = err2
|
|
return
|
|
}
|
|
|
|
remoteResponse = string(resBody)
|
|
|
|
return
|
|
}
|
|
|
|
// 复杂http请求
|
|
func HttpDo(httpMethod string, url string, headerMap map[string]string, rawBody string) (remoteResponse string, err error) {
|
|
|
|
_, cancel := context.WithTimeout(context.Background(), 20*time.Second)
|
|
defer cancel()
|
|
|
|
client := &http.Client{
|
|
Timeout: time.Second * 20, // 设置客户端超时为5秒
|
|
}
|
|
|
|
req, err0 := http.NewRequest(httpMethod, url, strings.NewReader(rawBody))
|
|
|
|
if err0 != nil {
|
|
|
|
err = err0
|
|
return
|
|
}
|
|
|
|
if len(headerMap) > 0 {
|
|
for k, v := range headerMap {
|
|
req.Header.Set(k, v)
|
|
}
|
|
}
|
|
|
|
resp, err1 := client.Do(req)
|
|
|
|
if err1 != nil {
|
|
err = err1
|
|
return
|
|
}
|
|
|
|
defer resp.Body.Close()
|
|
|
|
body, err2 := ioutil.ReadAll(resp.Body)
|
|
if err2 != nil {
|
|
err = err2
|
|
return
|
|
}
|
|
|
|
remoteResponse = string(body)
|
|
|
|
return
|
|
|
|
}
|
|
|
|
func CreateApiSign(params map[string]string, secret string) string {
|
|
|
|
keys := make([]string, 20)
|
|
for key, _ := range params {
|
|
if key == "Signature" {
|
|
continue
|
|
}
|
|
keys = append(keys, key)
|
|
}
|
|
//按key升序
|
|
sort.Strings(keys)
|
|
//把KEY值合并为字符串
|
|
waitSignString := ""
|
|
for _, value := range keys {
|
|
waitSignString += base64.StdEncoding.EncodeToString([]byte(params[value]))
|
|
}
|
|
//加上密钥
|
|
appSecret := secret
|
|
waitSignString += appSecret
|
|
|
|
// log.InfoF("waitSignString: %s", waitSignString)
|
|
//sha1加密
|
|
t := sha1.New()
|
|
io.WriteString(t, waitSignString)
|
|
sign := t.Sum(nil)
|
|
|
|
return hex.EncodeToString(sign)
|
|
|
|
}
|