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:

  1. You can use New to create a custom HTTP client object Client, which can then be used to execute requests. This object employs a connection pool design internally, so it does not have a Close method. An HTTP client object can also be created via the g.Client() shortcut method.
  2. The client provides a series of methods named after HTTP Methods. Invoking these methods will initiate the corresponding HTTP Method requests. The commonly used methods are Get and Post, while DoRequest is the core request method that users can call to implement custom HTTP Method requests.
  3. The result of the request is a *ClientResponse object. You can obtain the corresponding return results through this object. The ReadAll/ReadAllString methods can be used to obtain the returned content. After use, this object needs to be closed through the Close method to prevent memory overflow.
  4. The *Bytes method is used to obtain the binary data returned by the server. If the request fails, it returns nil; the *Content method is used to request string result data. If the request fails, it returns an empty string; the Set* method is for setting parameters of the Client.
  5. The *Var method 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 empty g.Var generic object is returned, which does not affect the invocation of conversion methods.
  6. As can be seen, the data parameter data for the client’s request parameters is of the interface{} type, meaning any data type can be passed. Common parameter data types are string/map. If the parameter is of map type, the parameter value will be automatically urlencode encoded.

HTTPClient - 图1warning

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):

  1. func (c *Client) Timeout(t time.Duration) *Client
  2. func (c *Client) Cookie(m map[string]string) *Client
  3. func (c *Client) Header(m map[string]string) *Client
  4. func (c *Client) HeaderRaw(headers string) *Client
  5. func (c *Client) ContentType(contentType string) *Client
  6. func (c *Client) ContentJson() *Client
  7. func (c *Client) ContentXml() *Client
  8. func (c *Client) BasicAuth(user, pass string) *Client
  9. func (c *Client) Retry(retryCount int, retryInterval time.Duration) *Client
  10. func (c *Client) Prefix(prefix string) *Client
  11. func (c *Client) Proxy(proxyURL string) *Client
  12. func (c *Client) RedirectLimit(redirectLimit int) *Client
  13. func (c *Client) Dump(dump ...bool) *Client
  14. func (c *Client) Use(handlers ...HandlerFunc) *Client

Brief Explanation:

  1. The Timeout method is used to set the current request timeout.
  2. The Cookie method is used to set custom Cookie information for the current request.
  3. The Header* methods are used to set custom Header information for the current request.
  4. The Content* methods are used to set the Content-Type information for the current request, and they support automatically checking submitted parameters and encoding according to this information.
  5. The BasicAuth method is used to set the HTTP Basic Auth validation information.
  6. The Retry method is used to set the number of retries and retry interval after a request failure.
  7. The Proxy method is used to set up an http access proxy.
  8. The RedirectLimit method 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:

  1. func (r *Response) GetCookie(key string) string
  2. func (r *Response) GetCookieMap() map[string]string
  3. func (r *Response) Raw() string
  4. func (r *Response) RawDump()
  5. func (r *Response) RawRequest() string
  6. func (r *Response) RawResponse() string
  7. func (r *Response) ReadAll() []byte
  8. func (r *Response) ReadAllString() string
  9. 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

  1. The ghttp client defaults to disabling the KeepAlive feature and the verification function for the server’s TLS certificate. If you need to enable it, you can customize the client’s Transport attribute.
  2. These advanced functions such as Connection Pool Parameter Setting and Connection Proxy Settings can also be achieved by customizing the client’s Transport attribute. This data inherits from the standard library’s http.Transport object.

Documentation

📄️ HTTPClient - ExamplesUse 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 UploadingUsing 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 - CookieCustomize 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 - HeaderWith 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 - ContentTypeUse 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 - TransportIn 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 - RawUse 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 - ProxySet 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 - MiddlewareThe 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 - FAQExplain 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 - MetricsThe 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.