|
1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677 |
- package utils
-
- import (
- "encoding/json"
- "fmt"
- "github.com/tal-tech/go-zero/core/logx"
- "io/ioutil"
- "net/http"
- "net/url"
- "strings"
- )
-
- type Callback func(result []byte) interface{}
-
- func HttpDoCallBack(reqUrl, method string, params map[string]string, header map[string]string, callback Callback) (data interface{}, err error) {
- body, err := HttpDo(reqUrl, method, params, header)
- if err != nil {
- logx.Errorf("method %s, reqUrl %s error %s", method, reqUrl, err)
- return nil, err
- }
- if len(body) > 0 {
- data = callback(body)
- return data, err
- }
- return nil, err
- }
-
- func HttpDo(reqUrl, method string, params map[string]string, header map[string]string) (data []byte, err error) {
- var paramStr []byte
- paramStr, _ = json.Marshal(params)
- client := &http.Client{}
- req, err := http.NewRequest(strings.ToUpper(method), reqUrl, strings.NewReader(string(paramStr)))
- if err != nil {
- logx.Errorf("method %s, reqUrl %s error %s", method, reqUrl, err)
- return nil, err
- }
- for k, v := range header {
- req.Header.Set(k, v)
- }
- resp, err := client.Do(req)
- if err != nil {
- logx.Errorf("method %s, reqUrl %s error %s", method, reqUrl, err)
- }
- defer resp.Body.Close()
-
- body, err := ioutil.ReadAll(resp.Body)
- if err != nil {
- logx.Errorf("method %s, reqUrl %s error %s", method, reqUrl, err)
- return nil, err
- }
- return body, nil
- }
-
- func GetParameterString(params map[string][]string) string {
- var paramStr = ""
- for k, v := range params {
- s, _ := url.QueryUnescape(strings.Join(v, ","))
- if len(paramStr) == 0 {
- paramStr = fmt.Sprintf("%s=%s", k, s)
- } else {
- paramStr = fmt.Sprintf("%s&%s=%s", paramStr, k, s)
- }
- }
- return paramStr
- }
-
- func GetSign(data, url string) string {
- reqMap := make(map[string]string)
- reqMap["obj"] = data
- headerMap := make(map[string]string)
- headerMap["Content-Type"] = "application/json"
- b, err := HttpDo(url, "POST", reqMap, headerMap)
- if err != nil {
- logx.Error(err)
- }
- return string(b)
- }
|