package req
import (
"bytes"
"context"
"crypto/tls"
"crypto/x509"
"encoding/json"
"encoding/xml"
"errors"
"fmt"
"io"
"net"
"net/http"
"net/http/cookiejar"
"net/netip"
urlpkg "net/url"
"os"
"reflect"
"strings"
"time"
utls "github.com/refraction-networking/utls"
"golang.org/x/net/publicsuffix"
"github.com/imroc/req/v3/http2"
"github.com/imroc/req/v3/internal/header"
"github.com/imroc/req/v3/internal/util"
"github.com/google/go-querystring/query"
)
func DefaultClient () *Client {
return defaultClient
}
func SetDefaultClient (c *Client ) {
if c != nil {
defaultClient = c
}
}
var defaultClient = C ()
type Client struct {
BaseURL string
PathParams map [string ]string
QueryParams urlpkg .Values
FormData urlpkg .Values
DebugLog bool
AllowGetMethodPayload bool
*Transport
digestAuth *digestAuth
cookiejarFactory func () http .CookieJar
trace bool
disableAutoReadResponse bool
maxResponseSize int64
commonErrorType reflect .Type
retryOption *RetryOption
jsonMarshal func (v any ) ([]byte , error )
jsonUnmarshal func (data []byte , v any ) error
xmlMarshal func (v any ) ([]byte , error )
xmlUnmarshal func (data []byte , v any ) error
multipartBoundaryFunc func () string
outputDirectory string
scheme string
log Logger
dumpOptions *DumpOptions
httpClient *http .Client
beforeRequest []RequestMiddleware
udBeforeRequest []RequestMiddleware
afterResponse []ResponseMiddleware
wrappedRoundTrip RoundTripper
roundTripWrappers []RoundTripWrapper
responseBodyTransformer func (rawBody []byte , req *Request , resp *Response ) (transformedBody []byte , err error )
resultStateCheckFunc func (resp *Response ) ResultState
onError ErrorHook
}
type ErrorHook func (client *Client , req *Request , resp *Response , err error )
func (c *Client ) R () *Request {
return &Request {
client : c ,
retryOption : c .retryOption .Clone (),
}
}
func (c *Client ) Get (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodGet
return r
}
func (c *Client ) Post (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodPost
return r
}
func (c *Client ) Patch (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodPatch
return r
}
func (c *Client ) Delete (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodDelete
return r
}
func (c *Client ) Put (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodPut
return r
}
func (c *Client ) Head (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodHead
return r
}
func (c *Client ) Options (url ...string ) *Request {
r := c .R ()
if len (url ) > 0 {
r .RawURL = url [0 ]
}
r .Method = http .MethodOptions
return r
}
func (c *Client ) GetTransport () *Transport {
return c .Transport
}
func (c *Client ) SetResponseBodyTransformer (fn func (rawBody []byte , req *Request , resp *Response ) (transformedBody []byte , err error )) *Client {
c .responseBodyTransformer = fn
return c
}
func (c *Client ) SetCommonError (err any ) *Client {
return c .SetCommonErrorResult (err )
}
func (c *Client ) SetCommonErrorResult (err any ) *Client {
if err != nil {
c .commonErrorType = util .GetType (err )
}
return c
}
type ResultState int
const (
SuccessState ResultState = iota
ErrorState
UnknownState
)
func (c *Client ) SetResultStateCheckFunc (fn func (resp *Response ) ResultState ) *Client {
c .resultStateCheckFunc = fn
return c
}
func (c *Client ) SetCommonFormDataFromValues (data urlpkg .Values ) *Client {
if c .FormData == nil {
c .FormData = urlpkg .Values {}
}
for k , v := range data {
for _ , kv := range v {
c .FormData .Add (k , kv )
}
}
return c
}
func (c *Client ) SetCommonFormData (data map [string ]string ) *Client {
if c .FormData == nil {
c .FormData = urlpkg .Values {}
}
for k , v := range data {
c .FormData .Set (k , v )
}
return c
}
func (c *Client ) SetMultipartBoundaryFunc (fn func () string ) *Client {
c .multipartBoundaryFunc = fn
return c
}
func (c *Client ) SetBaseURL (u string ) *Client {
c .BaseURL = strings .TrimRight (u , "/" )
return c
}
func (c *Client ) SetOutputDirectory (dir string ) *Client {
c .outputDirectory = dir
return c
}
func (c *Client ) SetCertFromFile (certFile , keyFile string ) *Client {
cert , err := tls .LoadX509KeyPair (certFile , keyFile )
if err != nil {
c .log .Errorf ("failed to load client cert: %v" , err )
return c
}
config := c .GetTLSClientConfig ()
config .Certificates = append (config .Certificates , cert )
return c
}
func (c *Client ) SetCerts (certs ...tls .Certificate ) *Client {
config := c .GetTLSClientConfig ()
config .Certificates = append (config .Certificates , certs ...)
return c
}
func (c *Client ) appendRootCertData (data []byte ) {
config := c .GetTLSClientConfig ()
if config .RootCAs == nil {
config .RootCAs = x509 .NewCertPool ()
}
config .RootCAs .AppendCertsFromPEM (data )
}
func (c *Client ) SetRootCertFromString (pemContent string ) *Client {
c .appendRootCertData ([]byte (pemContent ))
return c
}
func (c *Client ) SetRootCertsFromFile (pemFiles ...string ) *Client {
for _ , pemFile := range pemFiles {
rootPemData , err := os .ReadFile (pemFile )
if err != nil {
c .log .Errorf ("failed to read root cert file: %v" , err )
return c
}
c .appendRootCertData (rootPemData )
}
return c
}
func (c *Client ) GetTLSClientConfig () *tls .Config {
if c .TLSClientConfig == nil {
c .TLSClientConfig = &tls .Config {
NextProtos : []string {"h2" , "http/1.1" },
}
}
return c .TLSClientConfig
}
func (c *Client ) SetRedirectPolicy (policies ...RedirectPolicy ) *Client {
if len (policies ) == 0 {
return c
}
c .httpClient .CheckRedirect = func (req *http .Request , via []*http .Request ) error {
for _ , f := range policies {
if f == nil {
continue
}
err := f (req , via )
if err != nil {
return err
}
}
if c .DebugLog {
c .log .Debugf ("<redirect> %s %s" , req .Method , req .URL .String ())
}
return nil
}
return c
}
func (c *Client ) DisableKeepAlives () *Client {
c .Transport .DisableKeepAlives = true
return c
}
func (c *Client ) EnableKeepAlives () *Client {
c .Transport .DisableKeepAlives = false
return c
}
func (c *Client ) DisableCompression () *Client {
c .Transport .DisableCompression = true
return c
}
func (c *Client ) EnableCompression () *Client {
c .Transport .DisableCompression = false
return c
}
func (c *Client ) EnableAutoDecompress () *Client {
c .Transport .AutoDecompression = true
return c
}
func (c *Client ) DisableAutoDecompress () *Client {
c .Transport .AutoDecompression = false
return c
}
func (c *Client ) SetTLSClientConfig (conf *tls .Config ) *Client {
c .TLSClientConfig = conf
return c
}
func (c *Client ) EnableInsecureSkipVerify () *Client {
c .GetTLSClientConfig ().InsecureSkipVerify = true
return c
}
func (c *Client ) DisableInsecureSkipVerify () *Client {
c .GetTLSClientConfig ().InsecureSkipVerify = false
return c
}
func (c *Client ) SetCommonQueryParams (params map [string ]string ) *Client {
for k , v := range params {
c .SetCommonQueryParam (k , v )
}
return c
}
func (c *Client ) AddCommonQueryParam (key , value string ) *Client {
if c .QueryParams == nil {
c .QueryParams = make (urlpkg .Values )
}
c .QueryParams .Add (key , value )
return c
}
func (c *Client ) AddCommonQueryParams (key string , values ...string ) *Client {
if c .QueryParams == nil {
c .QueryParams = make (urlpkg .Values )
}
vs := c .QueryParams [key ]
vs = append (vs , values ...)
c .QueryParams [key ] = vs
return c
}
func (c *Client ) pathParams () map [string ]string {
if c .PathParams == nil {
c .PathParams = make (map [string ]string )
}
return c .PathParams
}
func (c *Client ) SetCommonPathParam (key , value string ) *Client {
c .pathParams ()[key ] = value
return c
}
func (c *Client ) SetCommonPathParams (pathParams map [string ]string ) *Client {
m := c .pathParams ()
for k , v := range pathParams {
m [k ] = v
}
return c
}
func (c *Client ) SetCommonQueryParam (key , value string ) *Client {
if c .QueryParams == nil {
c .QueryParams = make (urlpkg .Values )
}
c .QueryParams .Set (key , value )
return c
}
func (c *Client ) SetCommonQueryString (query string ) *Client {
params , err := urlpkg .ParseQuery (strings .TrimSpace (query ))
if err != nil {
c .log .Warnf ("failed to parse query string (%s): %v" , query , err )
return c
}
if c .QueryParams == nil {
c .QueryParams = make (urlpkg .Values )
}
for p , v := range params {
for _ , pv := range v {
c .QueryParams .Add (p , pv )
}
}
return c
}
func (c *Client ) SetCommonQueryParamsFromValues (params urlpkg .Values ) *Client {
if c .QueryParams == nil {
c .QueryParams = make (urlpkg .Values )
}
for p , v := range params {
for _ , pv := range v {
c .QueryParams .Add (p , pv )
}
}
return c
}
func (c *Client ) SetCommonQueryParamsFromStruct (v any ) *Client {
values , err := query .Values (v )
if err != nil {
c .log .Warnf ("failed to convert struct to query parameters: %v" , err )
return c
}
return c .SetCommonQueryParamsFromValues (values )
}
func (c *Client ) SetCommonCookies (cookies ...*http .Cookie ) *Client {
c .Cookies = append (c .Cookies , cookies ...)
return c
}
func (c *Client ) DisableDebugLog () *Client {
c .DebugLog = false
return c
}
func (c *Client ) EnableDebugLog () *Client {
c .DebugLog = true
return c
}
func (c *Client ) DevMode () *Client {
return c .EnableDumpAll ().
EnableDebugLog ().
EnableTraceAll ()
}
func (c *Client ) SetScheme (scheme string ) *Client {
if !util .IsStringEmpty (scheme ) {
c .scheme = strings .TrimSpace (scheme )
}
return c
}
func (c *Client ) GetLogger () Logger {
if c .log != nil {
return c .log
}
c .log = createDefaultLogger ()
return c .log
}
func (c *Client ) SetLogger (log Logger ) *Client {
if log == nil {
c .log = &disableLogger {}
return c
}
c .log = log
return c
}
func (c *Client ) SetTimeout (d time .Duration ) *Client {
c .httpClient .Timeout = d
return c
}
func (c *Client ) getDumpOptions () *DumpOptions {
if c .dumpOptions == nil {
c .dumpOptions = newDefaultDumpOptions ()
}
return c .dumpOptions
}
func (c *Client ) EnableDumpAll () *Client {
if c .Dump != nil {
return c
}
c .EnableDump (c .getDumpOptions ())
return c
}
func (c *Client ) EnableDumpAllToFile (filename string ) *Client {
file , err := os .Create (filename )
if err != nil {
c .log .Errorf ("create dump file error: %v" , err )
return c
}
c .getDumpOptions ().Output = file
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllTo (output io .Writer ) *Client {
c .getDumpOptions ().Output = output
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllAsync () *Client {
o := c .getDumpOptions ()
o .Async = true
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllWithoutRequestBody () *Client {
o := c .getDumpOptions ()
o .RequestBody = false
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllWithoutResponseBody () *Client {
o := c .getDumpOptions ()
o .ResponseBody = false
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllWithoutResponse () *Client {
o := c .getDumpOptions ()
o .ResponseBody = false
o .ResponseHeader = false
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllWithoutRequest () *Client {
o := c .getDumpOptions ()
o .RequestHeader = false
o .RequestBody = false
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllWithoutHeader () *Client {
o := c .getDumpOptions ()
o .RequestHeader = false
o .ResponseHeader = false
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpAllWithoutBody () *Client {
o := c .getDumpOptions ()
o .RequestBody = false
o .ResponseBody = false
c .EnableDumpAll ()
return c
}
func (c *Client ) EnableDumpEachRequest () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDump ()
}
return nil
})
}
func (c *Client ) EnableDumpEachRequestWithoutBody () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDumpWithoutBody ()
}
return nil
})
}
func (c *Client ) EnableDumpEachRequestWithoutHeader () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDumpWithoutHeader ()
}
return nil
})
}
func (c *Client ) EnableDumpEachRequestWithoutRequest () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDumpWithoutRequest ()
}
return nil
})
}
func (c *Client ) EnableDumpEachRequestWithoutResponse () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDumpWithoutResponse ()
}
return nil
})
}
func (c *Client ) EnableDumpEachRequestWithoutResponseBody () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDumpWithoutResponseBody ()
}
return nil
})
}
func (c *Client ) EnableDumpEachRequestWithoutRequestBody () *Client {
return c .OnBeforeRequest (func (client *Client , req *Request ) error {
if req .RetryAttempt == 0 {
req .EnableDumpWithoutRequestBody ()
}
return nil
})
}
func (c *Client ) NewRequest () *Request {
return c .R ()
}
func (c *Client ) NewParallelDownload (url string ) *ParallelDownload {
return &ParallelDownload {
url : url ,
client : c ,
}
}
func (c *Client ) DisableAutoReadResponse () *Client {
c .disableAutoReadResponse = true
return c
}
func (c *Client ) EnableAutoReadResponse () *Client {
c .disableAutoReadResponse = false
return c
}
func (c *Client ) SetMaxResponseSize (max int64 ) *Client {
if max < 0 {
max = 0
}
c .maxResponseSize = max
return c
}
func (c *Client ) SetAutoDecodeContentType (contentTypes ...string ) *Client {
c .Transport .SetAutoDecodeContentType (contentTypes ...)
return c
}
func (c *Client ) SetAutoDecodeContentTypeFunc (fn func (contentType string ) bool ) *Client {
c .Transport .SetAutoDecodeContentTypeFunc (fn )
return c
}
func (c *Client ) SetAutoDecodeAllContentType () *Client {
c .Transport .SetAutoDecodeAllContentType ()
return c
}
func (c *Client ) DisableAutoDecode () *Client {
c .Transport .DisableAutoDecode ()
return c
}
func (c *Client ) EnableAutoDecode () *Client {
c .Transport .EnableAutoDecode ()
return c
}
func (c *Client ) SetUserAgent (userAgent string ) *Client {
return c .SetCommonHeader (header .UserAgent , userAgent )
}
func (c *Client ) SetCommonBearerAuthToken (token string ) *Client {
return c .SetCommonHeader (header .Authorization , "Bearer " +token )
}
func (c *Client ) SetCommonBasicAuth (username , password string ) *Client {
c .SetCommonHeader (header .Authorization , util .BasicAuthHeaderValue (username , password ))
return c
}
func (c *Client ) SetCommonDigestAuth (username , password string ) *Client {
c .digestAuth = &digestAuth {
Username : username ,
Password : password ,
HttpClient : c .httpClient ,
cache : make (map [string ]*cchal ),
}
c .Transport .WrapRoundTripFunc (c .digestAuth .HttpRoundTripWrapperFunc )
return c
}
func (c *Client ) SetCommonHeaders (hdrs map [string ]string ) *Client {
for k , v := range hdrs {
c .SetCommonHeader (k , v )
}
return c
}
func (c *Client ) SetCommonHeader (key , value string ) *Client {
if c .Headers == nil {
c .Headers = make (http .Header )
}
c .Headers .Set (key , value )
return c
}
func (c *Client ) SetCommonHeaderNonCanonical (key , value string ) *Client {
if c .Headers == nil {
c .Headers = make (http .Header )
}
c .Headers [key ] = append (c .Headers [key ], value )
return c
}
func (c *Client ) SetCommonHeadersNonCanonical (hdrs map [string ]string ) *Client {
for k , v := range hdrs {
c .SetCommonHeaderNonCanonical (k , v )
}
return c
}
func (c *Client ) SetCommonHeaderOrder (keys ...string ) *Client {
c .Transport .WrapRoundTripFunc (func (rt http .RoundTripper ) HttpRoundTripFunc {
return func (req *http .Request ) (resp *http .Response , err error ) {
if req .Header == nil {
req .Header = make (http .Header )
}
req .Header [HeaderOderKey ] = keys
return rt .RoundTrip (req )
}
})
return c
}
func (c *Client ) SetCommonPseudoHeaderOder (keys ...string ) *Client {
c .Transport .WrapRoundTripFunc (func (rt http .RoundTripper ) HttpRoundTripFunc {
return func (req *http .Request ) (resp *http .Response , err error ) {
if req .Header == nil {
req .Header = make (http .Header )
}
req .Header [PseudoHeaderOderKey ] = keys
return rt .RoundTrip (req )
}
})
return c
}
func (c *Client ) SetHTTP2SettingsFrame (settings ...http2 .Setting ) *Client {
c .Transport .SetHTTP2SettingsFrame (settings ...)
return c
}
func (c *Client ) SetHTTP2ConnectionFlow (flow uint32 ) *Client {
c .Transport .SetHTTP2ConnectionFlow (flow )
return c
}
func (c *Client ) SetHTTP2HeaderPriority (priority http2 .PriorityParam ) *Client {
c .Transport .SetHTTP2HeaderPriority (priority )
return c
}
func (c *Client ) SetHTTP2PriorityFrames (frames ...http2 .PriorityFrame ) *Client {
c .Transport .SetHTTP2PriorityFrames (frames ...)
return c
}
func (c *Client ) SetCommonContentType (ct string ) *Client {
c .SetCommonHeader (header .ContentType , ct )
return c
}
func (c *Client ) DisableDumpAll () *Client {
c .DisableDump ()
return c
}
func (c *Client ) SetCommonDumpOptions (opt *DumpOptions ) *Client {
if opt == nil {
return c
}
if opt .Output == nil {
if c .dumpOptions != nil {
opt .Output = c .dumpOptions .Output
} else {
opt .Output = os .Stdout
}
}
c .dumpOptions = opt
if c .Dump != nil {
c .Dump .SetOptions (dumpOptions {opt })
}
return c
}
func (c *Client ) SetProxy (proxy func (*http .Request ) (*urlpkg .URL , error )) *Client {
c .Transport .SetProxy (proxy )
return c
}
func (c *Client ) OnError (hook ErrorHook ) *Client {
c .onError = hook
return c
}
func (c *Client ) OnBeforeRequest (m RequestMiddleware ) *Client {
c .udBeforeRequest = append (c .udBeforeRequest , m )
return c
}
func (c *Client ) OnAfterResponse (m ResponseMiddleware ) *Client {
c .afterResponse = append (c .afterResponse , m )
return c
}
func (c *Client ) SetProxyURL (proxyUrl string ) *Client {
if proxyUrl == "" {
c .log .Warnf ("ignore empty proxy url in SetProxyURL" )
return c
}
u , err := urlpkg .Parse (proxyUrl )
if err != nil {
c .log .Errorf ("failed to parse proxy url %s: %v" , proxyUrl , err )
return c
}
proxy := http .ProxyURL (u )
c .SetProxy (proxy )
return c
}
func (c *Client ) DisableTraceAll () *Client {
c .trace = false
return c
}
func (c *Client ) EnableTraceAll () *Client {
c .trace = true
return c
}
func (c *Client ) SetCookieJar (jar http .CookieJar ) *Client {
c .cookiejarFactory = nil
c .httpClient .Jar = jar
return c
}
func (c *Client ) GetCookies (url string ) ([]*http .Cookie , error ) {
if c .httpClient .Jar == nil {
return nil , errors .New ("cookie jar is not enabled" )
}
u , err := urlpkg .Parse (url )
if err != nil {
return nil , err
}
return c .httpClient .Jar .Cookies (u ), nil
}
func (c *Client ) ClearCookies () *Client {
c .initCookieJar ()
c .Cookies = nil
return c
}
func (c *Client ) SetJsonMarshal (fn func (v any ) ([]byte , error )) *Client {
c .jsonMarshal = fn
return c
}
func (c *Client ) SetJsonUnmarshal (fn func (data []byte , v any ) error ) *Client {
c .jsonUnmarshal = fn
return c
}
func (c *Client ) SetXmlMarshal (fn func (v any ) ([]byte , error )) *Client {
c .xmlMarshal = fn
return c
}
func (c *Client ) SetXmlUnmarshal (fn func (data []byte , v any ) error ) *Client {
c .xmlUnmarshal = fn
return c
}
func (c *Client ) SetDialTLS (fn func (ctx context .Context , network , addr string ) (net .Conn , error )) *Client {
c .Transport .SetDialTLS (fn )
return c
}
func (c *Client ) SetDial (fn func (ctx context .Context , network , addr string ) (net .Conn , error )) *Client {
c .Transport .SetDial (fn )
return c
}
func (c *Client ) SetTLSFingerprintChrome () *Client {
return c .SetTLSFingerprint (utls .HelloChrome_Auto )
}
func (c *Client ) SetTLSFingerprintFirefox () *Client {
return c .SetTLSFingerprint (utls .HelloFirefox_Auto )
}
func (c *Client ) SetTLSFingerprintEdge () *Client {
return c .SetTLSFingerprint (utls .HelloEdge_Auto )
}
func (c *Client ) SetTLSFingerprintQQ () *Client {
return c .SetTLSFingerprint (utls .HelloQQ_Auto )
}
func (c *Client ) SetTLSFingerprintSafari () *Client {
return c .SetTLSFingerprint (utls .HelloSafari_Auto )
}
func (c *Client ) SetTLSFingerprint360 () *Client {
return c .SetTLSFingerprint (utls .Hello360_Auto )
}
func (c *Client ) SetTLSFingerprintIOS () *Client {
return c .SetTLSFingerprint (utls .HelloIOS_Auto )
}
func (c *Client ) SetTLSFingerprintAndroid () *Client {
return c .SetTLSFingerprint (utls .HelloAndroid_11_OkHttp )
}
func (c *Client ) SetTLSFingerprintRandomized () *Client {
return c .SetTLSFingerprint (utls .HelloRandomized )
}
type uTLSConn struct {
*utls .UConn
}
func (conn *uTLSConn ) ConnectionState () tls .ConnectionState {
cs := conn .Conn .ConnectionState ()
return tls .ConnectionState {
Version : cs .Version ,
HandshakeComplete : cs .HandshakeComplete ,
DidResume : cs .DidResume ,
CipherSuite : cs .CipherSuite ,
NegotiatedProtocol : cs .NegotiatedProtocol ,
NegotiatedProtocolIsMutual : cs .NegotiatedProtocolIsMutual ,
ServerName : cs .ServerName ,
PeerCertificates : cs .PeerCertificates ,
VerifiedChains : cs .VerifiedChains ,
SignedCertificateTimestamps : cs .SignedCertificateTimestamps ,
OCSPResponse : cs .OCSPResponse ,
TLSUnique : cs .TLSUnique ,
}
}
func (c *Client ) SetTLSFingerprint (clientHelloID utls .ClientHelloID ) *Client {
c .setTLSFingerprint (clientHelloID , nil )
return c
}
func (c *Client ) setTLSFingerprint (clientHelloID utls .ClientHelloID , uTLSConnApply func (*uTLSConn ) error ) *Client {
fn := func (ctx context .Context , addr string , plainConn net .Conn ) (conn net .Conn , tlsState *tls .ConnectionState , err error ) {
colonPos := strings .LastIndex (addr , ":" )
if colonPos == -1 {
colonPos = len (addr )
}
hostname := addr [:colonPos ]
tlsConfig := c .GetTLSClientConfig ()
utlsConfig := &utls .Config {
ServerName : hostname ,
Rand : tlsConfig .Rand ,
Time : tlsConfig .Time ,
RootCAs : tlsConfig .RootCAs ,
NextProtos : tlsConfig .NextProtos ,
ClientCAs : tlsConfig .ClientCAs ,
InsecureSkipVerify : tlsConfig .InsecureSkipVerify ,
CipherSuites : tlsConfig .CipherSuites ,
SessionTicketsDisabled : tlsConfig .SessionTicketsDisabled ,
MinVersion : tlsConfig .MinVersion ,
MaxVersion : tlsConfig .MaxVersion ,
DynamicRecordSizingDisabled : tlsConfig .DynamicRecordSizingDisabled ,
KeyLogWriter : tlsConfig .KeyLogWriter ,
}
uconn := &uTLSConn {utls .UClient (plainConn , utlsConfig , clientHelloID )}
if uTLSConnApply != nil {
if err = uTLSConnApply (uconn ); err != nil {
return
}
}
err = uconn .HandshakeContext (ctx )
if err != nil {
return
}
cs := uconn .Conn .ConnectionState ()
conn = uconn
tlsState = &tls .ConnectionState {
Version : cs .Version ,
HandshakeComplete : cs .HandshakeComplete ,
DidResume : cs .DidResume ,
CipherSuite : cs .CipherSuite ,
NegotiatedProtocol : cs .NegotiatedProtocol ,
NegotiatedProtocolIsMutual : cs .NegotiatedProtocolIsMutual ,
ServerName : cs .ServerName ,
PeerCertificates : cs .PeerCertificates ,
VerifiedChains : cs .VerifiedChains ,
SignedCertificateTimestamps : cs .SignedCertificateTimestamps ,
OCSPResponse : cs .OCSPResponse ,
TLSUnique : cs .TLSUnique ,
}
return
}
c .Transport .SetTLSHandshake (fn )
return c
}
func (c *Client ) SetTLSFingerprintSpec (fn func () utls .ClientHelloSpec ) *Client {
c .setTLSFingerprint (utls .HelloCustom , func (conn *uTLSConn ) error {
spec := fn ()
return conn .ApplyPreset (&spec )
})
return c
}
func (c *Client ) SetTLSHandshake (fn func (ctx context .Context , addr string , plainConn net .Conn ) (conn net .Conn , tlsState *tls .ConnectionState , err error )) *Client {
c .Transport .SetTLSHandshake (fn )
return c
}
func (c *Client ) SetTLSHandshakeTimeout (timeout time .Duration ) *Client {
c .Transport .SetTLSHandshakeTimeout (timeout )
return c
}
func (c *Client ) EnableForceHTTP1 () *Client {
c .Transport .EnableForceHTTP1 ()
return c
}
func (c *Client ) EnableForceHTTP2 () *Client {
c .Transport .EnableForceHTTP2 ()
return c
}
func (c *Client ) EnableForceHTTP3 () *Client {
c .Transport .EnableForceHTTP3 ()
return c
}
func (c *Client ) DisableForceHttpVersion () *Client {
c .Transport .DisableForceHttpVersion ()
return c
}
func (c *Client ) EnableH2C () *Client {
c .Transport .EnableH2C ()
return c
}
func (c *Client ) DisableH2C () *Client {
c .Transport .DisableH2C ()
return c
}
func (c *Client ) DisableAllowGetMethodPayload () *Client {
c .AllowGetMethodPayload = false
return c
}
func (c *Client ) EnableAllowGetMethodPayload () *Client {
c .AllowGetMethodPayload = true
return c
}
func (c *Client ) isPayloadForbid (m string ) bool {
return (m == http .MethodGet && !c .AllowGetMethodPayload ) || m == http .MethodHead || m == http .MethodOptions
}
func (c *Client ) GetClient () *http .Client {
return c .httpClient
}
func (c *Client ) getRetryOption () *RetryOption {
if c .retryOption == nil {
c .retryOption = newDefaultRetryOption ()
}
return c .retryOption
}
func (c *Client ) SetCommonRetryCount (count int ) *Client {
c .getRetryOption ().MaxRetries = count
return c
}
func (c *Client ) SetCommonRetryInterval (getRetryIntervalFunc GetRetryIntervalFunc ) *Client {
c .getRetryOption ().GetRetryInterval = getRetryIntervalFunc
return c
}
func (c *Client ) SetCommonRetryFixedInterval (interval time .Duration ) *Client {
c .getRetryOption ().GetRetryInterval = func (resp *Response , attempt int ) time .Duration {
return interval
}
return c
}
func (c *Client ) SetCommonRetryBackoffInterval (min , max time .Duration ) *Client {
c .getRetryOption ().GetRetryInterval = backoffInterval (min , max )
return c
}
func (c *Client ) SetCommonRetryHook (hook RetryHookFunc ) *Client {
c .getRetryOption ().RetryHooks = []RetryHookFunc {hook }
return c
}
func (c *Client ) AddCommonRetryHook (hook RetryHookFunc ) *Client {
ro := c .getRetryOption ()
ro .RetryHooks = append (ro .RetryHooks , hook )
return c
}
func (c *Client ) SetCommonRetryCondition (condition RetryConditionFunc ) *Client {
c .getRetryOption ().RetryConditions = []RetryConditionFunc {condition }
return c
}
func (c *Client ) AddCommonRetryCondition (condition RetryConditionFunc ) *Client {
ro := c .getRetryOption ()
ro .RetryConditions = append (ro .RetryConditions , condition )
return c
}
func (c *Client ) SetUnixSocket (file string ) *Client {
return c .SetDial (func (ctx context .Context , network , addr string ) (net .Conn , error ) {
var d net .Dialer
return d .DialContext (ctx , "unix" , file )
})
}
func (c *Client ) SetResolver (r *net .Resolver ) *Client {
return c .SetDial (func (ctx context .Context , network , addr string ) (net .Conn , error ) {
d := net .Dialer {Resolver : r }
return d .DialContext (ctx , network , addr )
})
}
func (c *Client ) SetHosts (hosts map [string ]string ) *Client {
m := make (map [string ]string , len (hosts ))
invalid := make (map [string ]string )
for host , ipStr := range hosts {
key := hostsMapKey (host )
if key == "" {
continue
}
ip := net .ParseIP (strings .Trim (ipStr , "[]" ))
if ip == nil {
invalid [key ] = ipStr
continue
}
m [key ] = ip .String ()
}
c .SetDial (func (ctx context .Context , network , addr string ) (net .Conn , error ) {
host , port , err := net .SplitHostPort (addr )
if err != nil {
return nil , err
}
if _ , err := netip .ParseAddr (host ); err == nil {
var d net .Dialer
return d .DialContext (ctx , network , addr )
}
key := hostsMapKey (host )
if raw , bad := invalid [key ]; bad {
return nil , fmt .Errorf ("req: SetHosts: invalid IP address %q for host %q" , raw , host )
}
ip , ok := m [key ]
if !ok {
return nil , &net .DNSError {
Err : "no such host" ,
Name : host ,
IsNotFound : true ,
}
}
var d net .Dialer
return d .DialContext (ctx , network , net .JoinHostPort (ip , port ))
})
c .Transport .rejectProxyWithSetHosts = true
return c
}
func hostsMapKey(host string ) string {
host = strings .TrimSpace (host )
if host == "" {
return ""
}
if ascii , err := idnaASCII (host ); err == nil {
host = ascii
}
return strings .ToLower (host )
}
func (c *Client ) DisableHTTP3 () *Client {
c .Transport .DisableHTTP3 ()
return c
}
func (c *Client ) EnableHTTP3 () *Client {
c .Transport .EnableHTTP3 ()
return c
}
func (c *Client ) SetHTTP2MaxHeaderListSize (max uint32 ) *Client {
c .Transport .SetHTTP2MaxHeaderListSize (max )
return c
}
func (c *Client ) SetHTTP2StrictMaxConcurrentStreams (strict bool ) *Client {
c .Transport .SetHTTP2StrictMaxConcurrentStreams (strict )
return c
}
func (c *Client ) SetHTTP2ReadIdleTimeout (timeout time .Duration ) *Client {
c .Transport .SetHTTP2ReadIdleTimeout (timeout )
return c
}
func (c *Client ) SetHTTP2PingTimeout (timeout time .Duration ) *Client {
c .Transport .SetHTTP2PingTimeout (timeout )
return c
}
func (c *Client ) SetHTTP2WriteByteTimeout (timeout time .Duration ) *Client {
c .Transport .SetHTTP2WriteByteTimeout (timeout )
return c
}
func (c *Client ) Do (req *http .Request ) (*http .Response , error ) {
return c .httpClient .Do (req )
}
func NewClient () *Client {
return C ()
}
func (c *Client ) Clone () *Client {
cc := *c
cc .Transport = c .Transport .Clone ()
cc .initTransport ()
client := *c .httpClient
client .Transport = cc .Transport
cc .httpClient = &client
cc .initCookieJar ()
if len (cc .roundTripWrappers ) > 0 {
cc .wrappedRoundTrip = roundTripImpl {&cc }
for _ , w := range cc .roundTripWrappers {
cc .wrappedRoundTrip = w (cc .wrappedRoundTrip )
}
}
cc .PathParams = cloneMap (c .PathParams )
cc .QueryParams = cloneUrlValues (c .QueryParams )
cc .FormData = cloneUrlValues (c .FormData )
cc .beforeRequest = cloneSlice (c .beforeRequest )
cc .udBeforeRequest = cloneSlice (c .udBeforeRequest )
cc .afterResponse = cloneSlice (c .afterResponse )
cc .dumpOptions = c .dumpOptions .Clone ()
cc .retryOption = c .retryOption .Clone ()
return &cc
}
func memoryCookieJarFactory() http .CookieJar {
jar , _ := cookiejar .New (&cookiejar .Options {PublicSuffixList : publicsuffix .List })
return jar
}
func C () *Client {
t := T ()
httpClient := &http .Client {
Transport : t ,
Timeout : 2 * time .Minute ,
}
beforeRequest := []RequestMiddleware {
parseRequestHeader ,
parseRequestCookie ,
parseRequestURL ,
parseRequestBody ,
}
afterResponse := []ResponseMiddleware {
parseResponseBody ,
handleDownload ,
}
c := &Client {
AllowGetMethodPayload : true ,
beforeRequest : beforeRequest ,
afterResponse : afterResponse ,
log : createDefaultLogger (),
httpClient : httpClient ,
Transport : t ,
jsonMarshal : json .Marshal ,
jsonUnmarshal : json .Unmarshal ,
xmlMarshal : xml .Marshal ,
xmlUnmarshal : xml .Unmarshal ,
cookiejarFactory : memoryCookieJarFactory ,
}
c .SetRedirectPolicy (DefaultRedirectPolicy ())
c .initCookieJar ()
c .initTransport ()
return c
}
func (c *Client ) SetCookieJarFactory (factory func () http .CookieJar ) *Client {
c .cookiejarFactory = factory
c .initCookieJar ()
return c
}
func (c *Client ) initCookieJar () {
if c .cookiejarFactory == nil {
return
}
jar := c .cookiejarFactory ()
if jar != nil {
c .httpClient .Jar = jar
}
}
func (c *Client ) initTransport () {
c .Debugf = func (format string , v ...any ) {
if c .DebugLog {
c .log .Debugf (format , v ...)
}
}
}
type RoundTripper interface {
RoundTrip (*Request ) (*Response , error )
}
type RoundTripFunc func (req *Request ) (resp *Response , err error )
func (fn RoundTripFunc ) RoundTrip (req *Request ) (*Response , error ) {
return fn (req )
}
type RoundTripWrapper func (rt RoundTripper ) RoundTripper
type RoundTripWrapperFunc func (rt RoundTripper ) RoundTripFunc
func (f RoundTripWrapperFunc ) wrapper () RoundTripWrapper {
return func (rt RoundTripper ) RoundTripper {
return f (rt )
}
}
func (c *Client ) WrapRoundTripFunc (funcs ...RoundTripWrapperFunc ) *Client {
var wrappers []RoundTripWrapper
for _ , fn := range funcs {
wrappers = append (wrappers , fn .wrapper ())
}
return c .WrapRoundTrip (wrappers ...)
}
type roundTripImpl struct {
*Client
}
func (r roundTripImpl ) RoundTrip (req *Request ) (resp *Response , err error ) {
return r .roundTrip (req )
}
func (c *Client ) WrapRoundTrip (wrappers ...RoundTripWrapper ) *Client {
if len (wrappers ) == 0 {
return c
}
if c .wrappedRoundTrip == nil {
c .roundTripWrappers = wrappers
c .wrappedRoundTrip = roundTripImpl {c }
} else {
c .roundTripWrappers = append (c .roundTripWrappers , wrappers ...)
}
for _ , w := range wrappers {
c .wrappedRoundTrip = w (c .wrappedRoundTrip )
}
return c
}
func (c *Client ) roundTrip (r *Request ) (resp *Response , err error ) {
resp = &Response {Request : r }
defer func () {
if err != nil {
resp .Err = err
} else {
err = resp .Err
}
}()
if r .trace == nil && r .client .trace {
r .trace = &clientTrace {}
}
ctx := r .ctx
if r .trace != nil {
ctx = r .trace .createContext (r .Context ())
}
var host string
if h := r .getHeader ("Host" ); h != "" {
host = h
} else {
host = r .URL .Host
}
contentLength := int64 (len (r .Body ))
if r .contentLength != 0 {
contentLength = r .contentLength
}
var reqBody io .ReadCloser
if r .GetBody != nil {
reqBody , resp .Err = r .GetBody ()
if resp .Err != nil {
return
}
}
getBody := r .GetBody
if r .unReplayableBody != nil {
getBody = nil
}
req := &http .Request {
Method : r .Method ,
Header : r .Headers .Clone (),
URL : r .URL ,
Host : host ,
Proto : "HTTP/1.1" ,
ProtoMajor : 1 ,
ProtoMinor : 1 ,
ContentLength : contentLength ,
Body : reqBody ,
GetBody : getBody ,
Close : r .close ,
}
for _ , cookie := range r .Cookies {
req .AddCookie (cookie )
}
if r .isSaveResponse && r .downloadCallback != nil {
var wrap wrapResponseBodyFunc = func (rc io .ReadCloser ) io .ReadCloser {
return &callbackReader {
ReadCloser : rc ,
callback : func (read int64 ) {
r .downloadCallback (DownloadInfo {
Response : resp ,
DownloadedSize : read ,
})
},
lastTime : time .Now (),
interval : r .downloadCallbackInterval ,
}
}
if ctx == nil {
ctx = context .Background ()
}
ctx = context .WithValue (ctx , wrapResponseBodyKey , wrap )
}
if ctx != nil {
req = req .WithContext (ctx )
}
r .RawRequest = req
r .StartTime = time .Now ()
var httpResponse *http .Response
httpResponse , resp .Err = c .httpClient .Do (r .RawRequest )
resp .Response = httpResponse
if resp .Err == nil {
if err := applyMaxResponseSize (r , resp ); err != nil {
resp .Err = err
}
}
if resp .Err == nil && !c .disableAutoReadResponse && !r .isSaveResponse && !r .disableAutoReadResponse && resp .StatusCode > 199 {
resp .ToBytes ()
resp .Body = io .NopCloser (bytes .NewReader (resp .body ))
}
for _ , f := range c .afterResponse {
if e := f (c , resp ); e != nil {
resp .Err = e
}
}
return
}
func applyMaxResponseSize(r *Request , resp *Response ) error {
max := r .getMaxResponseSize ()
if max <= 0 || resp .Response == nil || resp .Body == nil {
return nil
}
if r .Method != http .MethodHead {
if cl := resp .ContentLength ; cl > max {
_ = resp .Body .Close ()
resp .Body = http .NoBody
return &ResponseBodyTooLargeError {Limit : max , ContentLength : cl }
}
}
resp .Body = &maxResponseBodyReader {
r : resp .Body ,
n : max ,
limit : max ,
}
return nil
}
The pages are generated with Golds v0.8.7 . (GOOS=linux GOARCH=amd64)
Golds is a Go 101 project developed by Tapir Liu .
PR and bug reports are welcome and can be submitted to the issue list .
Please follow @zigo_101 (reachable from the left QR code) to get the latest news of Golds .