请求设置超时时间

This commit is contained in:
白茶清欢 2022-05-02 15:30:55 +08:00
parent 2ac4f096d7
commit 509e764fbc
2 changed files with 23 additions and 1 deletions

View File

@ -22,6 +22,8 @@ const (
ContentTypeFormURLEncoded = "application/x-www-form-urlencoded"
// ContentTypeJSON json的请求方式
ContentTypeJSON = "application/json"
// ContentTypeDefault 默认的请求方式
ContentTypeDefault = ContentTypeJSON
)
const (
@ -33,6 +35,13 @@ const (
BodyTypeYaml = "yaml"
)
const (
// DefaultConnectTimeout 默认连接超时时间, 毫秒
DefaultConnectTimeout = 1000
// DefaultReadTimeout 默认读取超时时间, 毫秒
DefaultReadTimeout = 1000
)
// ApiRequestConfig api请求的配置
//
// Author : go_developer@163.com<白茶清欢>
@ -54,6 +63,7 @@ type ApiRequestConfig struct {
Body []byte `json:"-"` // 请求体
FullURL string `json:"full_url"` // 完整请求地址
Timeout Timeout `json:"timeout"` // 超时配置
ContentType string `json:"content_type"` // 请求方法
}
// Timeout 超时配置

View File

@ -158,7 +158,13 @@ func getHttpClient(apiConfig *ApiRequestConfig, header map[string]string) *httpc
for name, val := range header {
fullHeader[name] = val
}
return httpclient.NewHttpClient().WithHeaders(fullHeader)
if len(apiConfig.ContentType) == 0 {
apiConfig.ContentType = ContentTypeDefault
}
fullHeader["content-type"] = apiConfig.ContentType
return httpclient.NewHttpClient().WithHeaders(fullHeader).
WithOption(httpclient.OPT_CONNECTTIMEOUT_MS, time.Duration(apiConfig.Timeout.Connect)*time.Millisecond).
WithOption(httpclient.OPT_TIMEOUT, time.Duration(apiConfig.Timeout.Read)*time.Millisecond)
}
// buildRequestURLAndParam 构建完整请求URL与请求参数
@ -168,6 +174,12 @@ func getHttpClient(apiConfig *ApiRequestConfig, header map[string]string) *httpc
// Date : 21:55 2022/5/1
func buildRequestURLAndParam(apiConfig *ApiRequestConfig, header map[string]string, param map[string]interface{}) {
apiConfig.Method = strings.ToUpper(apiConfig.Method)
if apiConfig.Timeout.Connect == 0 {
apiConfig.Timeout.Connect = DefaultConnectTimeout
}
if apiConfig.Timeout.Read == 0 {
apiConfig.Timeout.Read = DefaultConnectTimeout
}
formatParam := make(map[string]interface{})
for paramName, paramValue := range param {
uriTemplate := "{" + paramName + "}"