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.
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.
Documentation
📄️ HTTPClient - Examples
Use the GoFrame framework to send GET, POST, DELETE requests through basic HTTP client operations and process the return values. This article also discusses how to send JSON data with the POST method, use multiple parameters, and map type parameters for requests. Additionally, it provides a brief introduction to *Bytes, *Content, and *Var methods to help developers handle HTTP requests and responses more conveniently.
📄️ HTTPClient - File Uploading
Using the GoFrame framework for HTTP client file uploading, a convenient file upload feature is implemented, and three major APIs are provided to support single and multiple file uploads. Detailed explanations of both server and client implementation code are provided, along with methods for custom file naming and standardized routing to receive uploaded files, suitable for scenarios requiring integration of file upload functionality.
📄️ HTTPClient - Cookie
Customize the Cookie content sent to the server using the HTTP client in the GoFrame framework, mainly implemented through the SetCookie and SetCookieMap methods. Demonstrated with simple server and client examples on how to set and receive custom Cookie parameters, achieving personalized HTTP client requests.
📄️ HTTPClient - Header
With the HTTPClient feature of the GoFrame framework, users can customize the Header information of HTTP requests. This article introduces how to set and send Headers using methods like SetHeader, SetHeaderMap, and SetHeaderRaw, thus implementing custom tracing information such as Span-Id and Trace-Id. Simple code examples demonstrate how the client interacts with the server and returns results.
📄️ HTTPClient - ContentType
Use HTTPClient in GoFrame framework to customize the request's ContentType. Through different operations like ContentJson and ContentXml, you can set the request's Content-Type to application/json and application/xml respectively. It also provides examples of customizing ContentType, helping developers flexibly set request parameters and encoding methods to meet different API request needs.
📄️ HTTPClient - Transport
In the GoFrame framework, advanced usage of HTTPClient is achieved through custom Transport. This includes methods of client-server communication using Unix Socket and specific implementations for setting the size of the client connection pool parameters. The examples provide a wealth of real code snippets to help developers better understand and apply these techniques.
📄️ HTTPClient - Raw
Use the HTTP client feature in the GoFrame framework to obtain and print raw input and output information of HTTP requests. The main methods include Raw, RawDump, RawRequest, and RawResponse, which are useful for debugging HTTP requests. The example demonstrates the method of sending POST requests using the GoFrame framework and printing the request and response.
📄️ HTTPClient - Proxy
Set proxy server addresses in the HTTP client of GoFrame framework, supporting both http and socks5 forms. Users can easily configure proxies through SetProxy and Proxy methods to access external resources, including examples of normal calls and chained calls, helping users quickly master the use of proxy functions.
📄️ HTTPClient - Middleware
The HTTPClient interceptor/middleware feature in the GoFrame framework can be used for global request interception and parameter validation. Through middleware, developers can insert custom logic in the pre and post phases of requests, modify submitted parameters or returned parameters, implement signature parameter injection, and more, ensuring the security of API parameters.
📄️ HTTPClient - FAQ
Explain how to effectively use the gclient.Client object in the GoFrame framework to improve efficiency and reduce resource usage. Includes suggestions for reusing the gclient.Client object and how to handle illegal character issues, demonstrated with examples on setting the correct ContentType.
📄️ HTTPClient - Metrics
The monitoring metrics feature of the HTTP client is disabled by default to avoid performance impact. It provides a variety of metrics for users to reference, such as the time cost of request execution, connection creation time, and the total size of request bytes, among others. These metrics are enabled only when the metric feature is globally enabled, helping users perform better performance analysis.