mirror of
https://github.com/duke-git/lancet.git
synced 2026-02-15 02:02:27 +08:00
feat: add context for httpClient SendRequest function
This commit is contained in:
@@ -14,6 +14,7 @@ package netutil
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"bytes"
|
"bytes"
|
||||||
|
"context"
|
||||||
"crypto/tls"
|
"crypto/tls"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"errors"
|
"errors"
|
||||||
@@ -110,22 +111,23 @@ type HttpClientConfig struct {
|
|||||||
Verbose bool
|
Verbose bool
|
||||||
}
|
}
|
||||||
|
|
||||||
// defaultHttpClientConfig defalut client config
|
// defaultHttpClientConfig defalut client config.
|
||||||
var defaultHttpClientConfig = &HttpClientConfig{
|
var defaultHttpClientConfig = &HttpClientConfig{
|
||||||
Compressed: false,
|
Compressed: false,
|
||||||
HandshakeTimeout: 20 * time.Second,
|
HandshakeTimeout: 20 * time.Second,
|
||||||
ResponseTimeout: 40 * time.Second,
|
ResponseTimeout: 40 * time.Second,
|
||||||
}
|
}
|
||||||
|
|
||||||
// HttpClient is used for sending http request
|
// HttpClient is used for sending http request.
|
||||||
type HttpClient struct {
|
type HttpClient struct {
|
||||||
*http.Client
|
*http.Client
|
||||||
TLS *tls.Config
|
TLS *tls.Config
|
||||||
Request *http.Request
|
Request *http.Request
|
||||||
Config HttpClientConfig
|
Config HttpClientConfig
|
||||||
|
Context context.Context
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHttpClient make a HttpClient instance
|
// NewHttpClient make a HttpClient instance.
|
||||||
func NewHttpClient() *HttpClient {
|
func NewHttpClient() *HttpClient {
|
||||||
client := &HttpClient{
|
client := &HttpClient{
|
||||||
Client: &http.Client{
|
Client: &http.Client{
|
||||||
@@ -141,7 +143,7 @@ func NewHttpClient() *HttpClient {
|
|||||||
return client
|
return client
|
||||||
}
|
}
|
||||||
|
|
||||||
// NewHttpClientWithConfig make a HttpClient instance with pass config
|
// NewHttpClientWithConfig make a HttpClient instance with pass config.
|
||||||
func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient {
|
func NewHttpClientWithConfig(config *HttpClientConfig) *HttpClient {
|
||||||
if config == nil {
|
if config == nil {
|
||||||
config = defaultHttpClientConfig
|
config = defaultHttpClientConfig
|
||||||
@@ -176,6 +178,11 @@ func (client *HttpClient) SendRequest(request *HttpRequest) (*http.Response, err
|
|||||||
rawUrl := request.RawURL
|
rawUrl := request.RawURL
|
||||||
|
|
||||||
req, err := http.NewRequest(request.Method, rawUrl, bytes.NewBuffer(request.Body))
|
req, err := http.NewRequest(request.Method, rawUrl, bytes.NewBuffer(request.Body))
|
||||||
|
|
||||||
|
if client.Context != nil {
|
||||||
|
req, err = http.NewRequestWithContext(client.Context, request.Method, rawUrl, bytes.NewBuffer(request.Body))
|
||||||
|
}
|
||||||
|
|
||||||
if err != nil {
|
if err != nil {
|
||||||
return nil, err
|
return nil, err
|
||||||
}
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user