github.com/wangyougui/gf/v2@v2.6.5/net/gclient/gclient_config.go (about)

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