gopkg/request/curl.go

112 lines
2.9 KiB
Go

// Package request...
//
// Description : http 请求
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2021-08-01 8:47 下午
package request
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"time"
"github.com/tidwall/gjson"
"github.com/ddliu/go-httpclient"
)
// Send 发送HTTP请求
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 9:38 下午 2021/8/11
func Send(apiMethod *APIMethod) *APIResponse {
return nil
}
// request 发送请求
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2:27 下午 2021/8/12
func request(method string, fullURL string, parameter map[string]interface{}, header map[string]string, responseConfig *ResponseConfig) (*APIResponse, bool) {
apiResponse := &APIResponse{
Code: "",
Message: "",
Data: "",
Success: false,
TraceID: "",
Cost: 0,
RealCost: 0,
TotalCost: 0,
TotalRealCost: 0,
ErrorList: make([]error, 0),
StartRequestTime: time.Now().Unix(),
FinishRequestTime: 0,
}
defer func(apiResponse *APIResponse) {
apiResponse.FinishRequestTime = time.Now().Unix()
apiResponse.RealCost = apiResponse.FinishRequestTime - apiResponse.StartRequestTime
}(apiResponse)
if nil == parameter {
parameter = make(map[string]interface{})
}
if nil == header {
header = make(map[string]string)
}
var (
client *httpclient.HttpClient
response *httpclient.Response
err error
responseData []byte
)
client = httpclient.NewHttpClient().WithHeaders(header)
inputByteData, _ := json.Marshal(parameter)
requestData := bytes.NewReader(inputByteData)
if response, err = client.Do(method, fullURL, header, requestData); nil != err {
apiResponse.ErrorList = append(apiResponse.ErrorList, err)
return apiResponse, false
}
if responseData, err = ioutil.ReadAll(response.Body); nil != err {
return apiResponse, false
}
orgData := string(responseData)
apiResponse.Data = gjson.Get(orgData, responseConfig.DataKey).String()
apiResponse.Code = fmt.Sprintf("%v", gjson.Get(orgData, responseConfig.CodeKey).Value())
apiResponse.Message = gjson.Get(orgData, responseConfig.MessageKey).String()
apiResponse.Cost = gjson.Get(orgData, responseConfig.CostKey).Int()
return apiResponse, false
}
// isNeedRetry 是否需要重试
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 3:01 下午 2021/8/12
func isNeedRetry(apiMethod *APIMethod, errType string) bool {
return false
}
// buildResponseData 构建响应结果
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 2:57 下午 2021/8/12
func buildResponseData(response *httpclient.Response) *APIResponse {
return nil
}
// buildRequestHeader 构建请求header
//
// Author : go_developer@163.com<白茶清欢>
//
// Date : 9:41 下午 2021/8/11
func buildRequestHeader(apiMethod *APIMethod) map[string]string {
header := make(map[string]string)
return header
}