github.com/zhongdalu/gf@v1.0.0/g/net/ghttp/ghttp_client_config.go (about)

     1  // Copyright 2017 gf Author(https://github.com/zhongdalu/gf). 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/zhongdalu/gf.
     6  
     7  // HTTP客户端请求.
     8  
     9  package ghttp
    10  
    11  import (
    12  	"github.com/zhongdalu/gf/g/text/gregex"
    13  	"strings"
    14  	"time"
    15  )
    16  
    17  // 是否模拟浏览器模式(自动保存提交COOKIE)
    18  func (c *Client) SetBrowserMode(enabled bool) {
    19  	c.browserMode = enabled
    20  }
    21  
    22  // 设置HTTP Header
    23  func (c *Client) SetHeader(key, value string) {
    24  	c.header[key] = value
    25  }
    26  
    27  // 通过字符串设置HTTP Header
    28  func (c *Client) SetHeaderRaw(header string) {
    29  	for _, line := range strings.Split(strings.TrimSpace(header), "\n") {
    30  		array, _ := gregex.MatchString(`^([\w\-]+):\s*(.+)`, line)
    31  		if len(array) >= 3 {
    32  			c.header[array[1]] = array[2]
    33  		}
    34  	}
    35  }
    36  
    37  // 设置COOKIE
    38  func (c *Client) SetCookie(key, value string) {
    39  	c.cookies[key] = value
    40  }
    41  
    42  // 使用Map设置COOKIE
    43  func (c *Client) SetCookieMap(cookieMap map[string]string) {
    44  	for k, v := range cookieMap {
    45  		c.cookies[k] = v
    46  	}
    47  }
    48  
    49  // 设置请求的URL前缀
    50  func (c *Client) SetPrefix(prefix string) {
    51  	c.prefix = prefix
    52  }
    53  
    54  // 设置请求过期时间
    55  func (c *Client) SetTimeOut(t time.Duration) {
    56  	c.Timeout = t
    57  }
    58  
    59  // 设置HTTP访问账号密码
    60  func (c *Client) SetBasicAuth(user, pass string) {
    61  	c.authUser = user
    62  	c.authPass = pass
    63  }
    64  
    65  // 设置失败重试次数及间隔,失败仅针对网络请求失败情况。
    66  // 重试间隔时间单位为秒。
    67  func (c *Client) SetRetry(retryCount int, retryInterval int) {
    68  	c.retryCount = retryCount
    69  	c.retryInterval = retryInterval
    70  }
    71  
    72  // 链式操作, See SetBrowserMode
    73  func (c *Client) BrowserMode(enabled bool) *Client {
    74  	c.browserMode = enabled
    75  	return c
    76  }
    77  
    78  // 链式操作, See SetTimeOut
    79  func (c *Client) TimeOut(t time.Duration) *Client {
    80  	c.Timeout = t
    81  	return c
    82  }
    83  
    84  // 链式操作, See SetBasicAuth
    85  func (c *Client) BasicAuth(user, pass string) *Client {
    86  	c.authUser = user
    87  	c.authPass = pass
    88  	return c
    89  }
    90  
    91  // 链式操作, See SetRetry
    92  func (c *Client) Retry(retryCount int, retryInterval int) *Client {
    93  	c.retryCount = retryCount
    94  	c.retryInterval = retryInterval
    95  	return c
    96  }