HTTPClient
Introduction
The GoFrame framework offers a powerful and easy-to-use HTTP client, implemented by the gclient component. Object creation can be done through the package method gclient.New() or by calling the g.Client() method. It is recommended to use g.Client() to conveniently create an HTTP client object. Since gclient.Client is internally extended from the standard library‘s http.Client object, any features present in http.Client are also supported by gclient.Client.
Method List : https://pkg.go.dev/github.com/gogf/gf/v2/net/gclient
Brief Explanation :
- You can use
Newto create a custom HTTP client objectClient, which can then be used to execute requests. This object employs a connection pool design internally, so it does not have aClosemethod. AnHTTPclient object can also be created via theg.Client()shortcut method. - The client provides a series of methods named after
HTTP Methods. Invoking these methods will initiate the correspondingHTTP Methodrequests. The commonly used methods areGetandPost, whileDoRequestis the core request method that users can call to implement customHTTP Methodrequests. - The result of the request is a
*ClientResponseobject. You can obtain the corresponding return results through this object. TheReadAll/ReadAllStringmethods can be used to obtain the returned content. After use, this object needs to be closed through theClosemethod to prevent memory overflow. - The
*Bytesmethod is used to obtain the binary data returned by the server. If the request fails, it returnsnil; the*Contentmethod is used to request string result data. If the request fails, it returns an empty string; theSet*method is for setting parameters of theClient. - The
*Varmethod directly requests and retrieves HTTP API results as a generic type for easy conversion. If the request fails or the request result is empty, an emptyg.Vargeneric object is returned, which does not affect the invocation of conversion methods. - As can be seen, the data parameter
datafor the client‘s request parameters is of theinterface{}type, meaning any data type can be passed. Common parameter data types arestring/map. If the parameter is ofmaptype, the parameter value will be automaticallyurlencodeencoded.
warning
Please use the given methods to create a Client object, and do not use new(ghttp.Client) or &ghttp.Client{} to create a client object, otherwise, hmm.
Chain Operations
The client in the GoFrame framework supports convenient chain operations. The commonly used methods are as follows (the document method list may lag behind the source code, so it is recommended to check the API documentation or source code https://pkg.go.dev/github.com/gogf/gf/v2/net/gclient):
func (c *Client) Timeout(t time.Duration) *Client
func (c *Client) Cookie(m map[string]string) *Client
func (c *Client) Header(m map[string]string) *Client
func (c *Client) HeaderRaw(headers string) *Client
func (c *Client) ContentType(contentType string) *Client
func (c *Client) ContentJson() *Client
func (c *Client) ContentXml() *Client
func (c *Client) BasicAuth(user, pass string) *Client
func (c *Client) Retry(retryCount int, retryInterval time.Duration) *Client
func (c *Client) Prefix(prefix string) *Client
func (c *Client) Proxy(proxyURL string) *Client
func (c *Client) RedirectLimit(redirectLimit int) *Client
func (c *Client) Dump(dump ...bool) *Client
func (c *Client) Use(handlers ...HandlerFunc) *Client
Brief Explanation:
- The
Timeoutmethod is used to set the current request timeout. - The
Cookiemethod is used to set customCookieinformation for the current request. - The
Header*methods are used to set customHeaderinformation for the current request. - The
Content*methods are used to set theContent-Typeinformation for the current request, and they support automatically checking submitted parameters and encoding according to this information. - The
BasicAuthmethod is used to set theHTTP Basic Authvalidation information. - The
Retrymethod is used to set the number of retries and retry interval after a request failure. - The
Proxymethod is used to set up an http access proxy. - The
RedirectLimitmethod is used to limit the number of redirect hops.
Return Objects
gclient.Response is the corresponding return result object of an HTTP request, which inherits from http.Response and can use all methods of http.Response. It also adds the following methods:
func (r *Response) GetCookie(key string) string
func (r *Response) GetCookieMap() map[string]string
func (r *Response) Raw() string
func (r *Response) RawDump()
func (r *Response) RawRequest() string
func (r *Response) RawResponse() string
func (r *Response) ReadAll() []byte
func (r *Response) ReadAllString() string
func (r *Response) Close() error
It should be noted that Response requires a manual call to the Close method to close it. This means that regardless of whether you use the returned Response object or not, you need to assign this return object to a variable and manually call its Close method for closure (often using defer r.Close()), otherwise, it will cause file handle overflow and memory overflow.
Important Notes
- The
ghttpclient defaults to disabling theKeepAlivefeature and the verification function for the server‘sTLScertificate. If you need to enable it, you can customize the client’sTransportattribute. - These advanced functions such as Connection Pool Parameter Setting and Connection Proxy Settings can also be achieved by customizing the client‘s
Transportattribute. This data inherits from the standard library’shttp.Transportobject.
