gclient_config.go 5.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199
  1. // Copyright GoFrame Author(https://goframe.org). All Rights Reserved.
  2. //
  3. // This Source Code Form is subject to the terms of the MIT License.
  4. // If a copy of the MIT was not distributed with this file,
  5. // You can obtain one at https://github.com/gogf/gf.
  6. package gclient
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "net"
  11. "net/http"
  12. "net/http/cookiejar"
  13. "net/url"
  14. "strings"
  15. "time"
  16. "golang.org/x/net/proxy"
  17. "github.com/gogf/gf/v2/errors/gerror"
  18. "github.com/gogf/gf/v2/internal/intlog"
  19. "github.com/gogf/gf/v2/text/gregex"
  20. "github.com/gogf/gf/v2/text/gstr"
  21. )
  22. // SetBrowserMode enables browser mode of the client.
  23. // When browser mode is enabled, it automatically saves and sends cookie content
  24. // from and to server.
  25. func (c *Client) SetBrowserMode(enabled bool) *Client {
  26. if enabled {
  27. jar, _ := cookiejar.New(nil)
  28. c.Jar = jar
  29. }
  30. return c
  31. }
  32. // SetHeader sets a custom HTTP header pair for the client.
  33. func (c *Client) SetHeader(key, value string) *Client {
  34. c.header[key] = value
  35. return c
  36. }
  37. // SetHeaderMap sets custom HTTP headers with map.
  38. func (c *Client) SetHeaderMap(m map[string]string) *Client {
  39. for k, v := range m {
  40. c.header[k] = v
  41. }
  42. return c
  43. }
  44. // SetAgent sets the User-Agent header for client.
  45. func (c *Client) SetAgent(agent string) *Client {
  46. c.header[httpHeaderUserAgent] = agent
  47. return c
  48. }
  49. // SetContentType sets HTTP content type for the client.
  50. func (c *Client) SetContentType(contentType string) *Client {
  51. c.header[httpHeaderContentType] = contentType
  52. return c
  53. }
  54. // SetHeaderRaw sets custom HTTP header using raw string.
  55. func (c *Client) SetHeaderRaw(headers string) *Client {
  56. for _, line := range gstr.SplitAndTrim(headers, "\n") {
  57. array, _ := gregex.MatchString(httpRegexHeaderRaw, line)
  58. if len(array) >= 3 {
  59. c.header[array[1]] = array[2]
  60. }
  61. }
  62. return c
  63. }
  64. // SetCookie sets a cookie pair for the client.
  65. func (c *Client) SetCookie(key, value string) *Client {
  66. c.cookies[key] = value
  67. return c
  68. }
  69. // SetCookieMap sets cookie items with map.
  70. func (c *Client) SetCookieMap(m map[string]string) *Client {
  71. for k, v := range m {
  72. c.cookies[k] = v
  73. }
  74. return c
  75. }
  76. // SetPrefix sets the request server URL prefix.
  77. func (c *Client) SetPrefix(prefix string) *Client {
  78. c.prefix = prefix
  79. return c
  80. }
  81. // SetTimeout sets the request timeout for the client.
  82. func (c *Client) SetTimeout(t time.Duration) *Client {
  83. c.Client.Timeout = t
  84. return c
  85. }
  86. // SetBasicAuth sets HTTP basic authentication information for the client.
  87. func (c *Client) SetBasicAuth(user, pass string) *Client {
  88. c.authUser = user
  89. c.authPass = pass
  90. return c
  91. }
  92. // SetRetry sets retry count and interval.
  93. func (c *Client) SetRetry(retryCount int, retryInterval time.Duration) *Client {
  94. c.retryCount = retryCount
  95. c.retryInterval = retryInterval
  96. return c
  97. }
  98. // SetRedirectLimit limits the number of jumps.
  99. func (c *Client) SetRedirectLimit(redirectLimit int) *Client {
  100. c.CheckRedirect = func(req *http.Request, via []*http.Request) error {
  101. if len(via) >= redirectLimit {
  102. return http.ErrUseLastResponse
  103. }
  104. return nil
  105. }
  106. return c
  107. }
  108. // SetProxy set proxy for the client.
  109. // This func will do nothing when the parameter `proxyURL` is empty or in wrong pattern.
  110. // The correct pattern is like `http://USER:PASSWORD@IP:PORT` or `socks5://USER:PASSWORD@IP:PORT`.
  111. // Only `http` and `socks5` proxies are supported currently.
  112. func (c *Client) SetProxy(proxyURL string) {
  113. if strings.TrimSpace(proxyURL) == "" {
  114. return
  115. }
  116. _proxy, err := url.Parse(proxyURL)
  117. if err != nil {
  118. intlog.Errorf(context.TODO(), `%+v`, err)
  119. return
  120. }
  121. if _proxy.Scheme == httpProtocolName {
  122. if v, ok := c.Transport.(*http.Transport); ok {
  123. v.Proxy = http.ProxyURL(_proxy)
  124. }
  125. } else {
  126. auth := &proxy.Auth{}
  127. user := _proxy.User.Username()
  128. if user != "" {
  129. auth.User = user
  130. password, hasPassword := _proxy.User.Password()
  131. if hasPassword && password != "" {
  132. auth.Password = password
  133. }
  134. } else {
  135. auth = nil
  136. }
  137. // refer to the source code, error is always nil
  138. dialer, err := proxy.SOCKS5(
  139. "tcp",
  140. _proxy.Host,
  141. auth,
  142. &net.Dialer{
  143. Timeout: c.Client.Timeout,
  144. KeepAlive: c.Client.Timeout,
  145. },
  146. )
  147. if err != nil {
  148. intlog.Errorf(context.TODO(), `%+v`, err)
  149. return
  150. }
  151. if v, ok := c.Transport.(*http.Transport); ok {
  152. v.DialContext = func(ctx context.Context, network, addr string) (conn net.Conn, e error) {
  153. return dialer.Dial(network, addr)
  154. }
  155. }
  156. // c.SetTimeout(10*time.Second)
  157. }
  158. }
  159. // SetTLSKeyCrt sets the certificate and key file for TLS configuration of client.
  160. func (c *Client) SetTLSKeyCrt(crtFile, keyFile string) error {
  161. tlsConfig, err := LoadKeyCrt(crtFile, keyFile)
  162. if err != nil {
  163. return gerror.Wrap(err, "LoadKeyCrt failed")
  164. }
  165. if v, ok := c.Transport.(*http.Transport); ok {
  166. tlsConfig.InsecureSkipVerify = true
  167. v.TLSClientConfig = tlsConfig
  168. return nil
  169. }
  170. return gerror.New(`cannot set TLSClientConfig for custom Transport of the client`)
  171. }
  172. // SetTLSConfig sets the TLS configuration of client.
  173. func (c *Client) SetTLSConfig(tlsConfig *tls.Config) error {
  174. if v, ok := c.Transport.(*http.Transport); ok {
  175. v.TLSClientConfig = tlsConfig
  176. return nil
  177. }
  178. return gerror.New(`cannot set TLSClientConfig for custom Transport of the client`)
  179. }