From 509e764fbc3848433bc61ae337263e3e66371983 Mon Sep 17 00:00:00 2001 From: =?UTF-8?q?=E7=99=BD=E8=8C=B6=E6=B8=85=E6=AC=A2?= Date: Mon, 2 May 2022 15:30:55 +0800 Subject: [PATCH] =?UTF-8?q?=E8=AF=B7=E6=B1=82=E8=AE=BE=E7=BD=AE=E8=B6=85?= =?UTF-8?q?=E6=97=B6=E6=97=B6=E9=97=B4?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- curl/define.go | 10 ++++++++++ curl/request.go | 14 +++++++++++++- 2 files changed, 23 insertions(+), 1 deletion(-) diff --git a/curl/define.go b/curl/define.go index facbfa2..c66c265 100644 --- a/curl/define.go +++ b/curl/define.go @@ -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 超时配置 diff --git a/curl/request.go b/curl/request.go index f317ad5..44787f9 100644 --- a/curl/request.go +++ b/curl/request.go @@ -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 + "}"