gclient_config.go 5.6 KB

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