Request input relies on the ghttp.Request object, which inherits from the underlying http.Request object. The ghttp.Request contains a corresponding response output object Response for the current request, used for data return processing.

Related methods: https://pkg.go.dev/github.com/gogf/gf/v2/net/ghttp#Request

Brief Introduction

As you can see, the parameter retrieval methods of the Request object are quite abundant, with common methods as follows:

Common MethodsDescription
GetA common method for simplified parameter retrieval, alias for GetRequest.
GetQueryRetrieves parameters passed via GET method, including Query String and Body parameter parsing.
GetFormRetrieves parameters passed via form method. The Content-Type for form submissions is often application/x-www-form-urlencoded, application/form-data, multipart/form-data, multipart/mixed, etc.
GetRequestRetrieves all parameters submitted by the client, covering parameters based on priority without distinguishing submission methods.
GetStructBinds all request parameters of a specified submission type to a specified struct object. Note that the given parameter is a pointer to an object. In most scenarios, the Parse method is often used to convert request data into a request object, as detailed in subsequent chapters.
GetBody/GetBodyStringRetrieves the raw data submitted by the client; this data is the raw data written into the body by the client, regardless of HTTP Method, for instance, when the client submits JSON/XML data format, this method can be used to get the original submitted data.
GetJsonAutomatically parses the original request information into a gjson.Json object pointer and returns it. The gjson.Json object is specifically introduced in the chapter General Codec.
ExitUsed for request flow control exit, as detailed in the subsequent explanations in this chapter.

Submission Method

In the GoFrame framework, parameter retrieval is not distinguished by HTTP Method but by parameter submission type. For example, when form parameters are submitted via HTTP Method: POST, INPUT, DELETE, the parameters are retrieved on the server side not through GetPost/GetInput/GetDelete, but uniformly through GetForm method for form parameters, which applies similarly to other HTTP Methods.

Under the GoFrame framework, there are several submission types:

Submission TypeDescription
RouterRoute Parameters. Derived from route rule matching.
QueryQuery Parameters. Parsing Query String parameters in URL, such as id=1&name=john in http://127.0.0.1/index?id=1&name=john.
FormForm Parameters. The most common submission method, with the submitted Content-Type often being: application/x-www-form-urlencoded, multipart/form-data, multipart/mixed.
BodyContent Parameters. Parameters obtained and parsed from Body, JSON/XML requests often use this method for submission.
CustomCustom Parameters, usually managed in server-side middleware or service functions via SetParam/GetParam methods.

Parameter Type

The parameter retrieval methods can automatically convert types of data with specified keys, for example: http://127.0.0.1:8199/?amount=19.66, retrieving with Get(xxx).String() will return the string type 19.66, while Get(xxx).Float32()/Get(xxx).Float64() will respectively return the float32 and float64 numeric type 19.66. However, Get(xxx).Int()/Get(xxx).Uint() will return 19 (if the parameter is a string of float type, it will be converted to integer by rounding down).

Request 🔥 - 图1tip

Smart of you to notice that all retrieved parameters are generic variables, and based on these generic variables, you can call corresponding methods to convert them into respective data types according to your needs.

Usage example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/", func(r *ghttp.Request) {
  9. r.Response.Writeln(r.Get("amount").String())
  10. r.Response.Writeln(r.Get("amount").Int())
  11. r.Response.Writeln(r.Get("amount").Float32())
  12. })
  13. s.SetPort(8199)
  14. s.Run()
  15. }

After execution, visiting the address http://127.0.0.1:8199/?amount=19.66 outputs:

  1. 19.66
  2. 19
  3. 19.66

Parameter Priority

Let’s consider a scenario, what happens when parameters with the same name exist in different submission methods? In the GoFrame framework, according to different retrieval methods, it acquires them based on different priorities, the parameter submitted by the method with higher priority will override the same-named parameters from other methods. The priority rules are as follows:

  1. Get and GetRequest methods: Router < Query < Body < Form < Custom, meaning custom parameters have the highest priority, followed by Form parameters, then Body parameters, and so on. For example, if both Query and Form submit parameters with the same name, id, with values 1 and 2 respectively, Get("id")/GetForm("id") will return 2, while GetQuery("id") will return 1.
  2. GetQuery method: Query > Body, meaning query string parameters override same-named parameters in Body. For instance, Query and Body both submit a parameter named id with values 1 and 2, respectively, Get("id") will return 2, and GetQuery("id") will return 1.
  3. GetForm method: Since this method is only for retrieving Form parameters, there isn’t much priority difference.

Usage example:

  1. package main
  2. import (
  3. "github.com/gogf/gf/v2/frame/g"
  4. "github.com/gogf/gf/v2/net/ghttp"
  5. )
  6. func main() {
  7. s := g.Server()
  8. s.BindHandler("/input", func(r *ghttp.Request) {
  9. r.Response.Writeln(r.Get("amount"))
  10. })
  11. s.BindHandler("/query", func(r *ghttp.Request) {
  12. r.Response.Writeln(r.GetQuery("amount"))
  13. })
  14. s.SetPort(8199)
  15. s.Run()
  16. }

After execution, we test using the curl tool:

  1. $ curl -d "amount=1" -X POST "http://127.0.0.1:8199/input?amount=100"
  2. 1
  3. $ curl -d "amount=1" -X POST "http://127.0.0.1:8199/query?amount=100"
  4. 100

As observed, when accessing the /input route, the method used the Get method to retrieve the amount parameter, according to the same-name priority rule, returning 1, the parameter passed in the body. When accessing through the /query route, the method internally used the GetQuery method to get the amount parameter, thus it retrieved the query string parameter’s amount value, returning 100.

Case Sensitivity

It is important to note that parameter names are case-sensitive, for instance, parameters name and Name submitted by the client are two different parameters. Since the server-side retrieves parameters by string name by default, case sensitivity doesn’t pose much issue, but it might need some attention if the server-side is receiving an API object. Let’s look at an example.

Server-side:

  1. package main
  2. import (
  3. "context"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/net/ghttp"
  6. )
  7. type Controller struct{}
  8. type PathReq struct {
  9. g.Meta `path:"/api/v1/*path" method:"post"`
  10. Path string
  11. }
  12. type PathRes struct {
  13. Path string
  14. }
  15. func (c *Controller) Path(ctx context.Context, req *PathReq) (res *PathRes, err error) {
  16. return &PathRes{Path: req.Path}, nil
  17. }
  18. func main() {
  19. s := g.Server()
  20. s.SetPort(8199)
  21. s.Use(ghttp.MiddlewareHandlerResponse)
  22. s.Group("/", func(group *ghttp.RouterGroup) {
  23. group.Bind(&Controller{})
  24. })
  25. s.Run()
  26. }

The original intention of the server-side API design is to define a route parameter path and receive it through the Path attribute of the API object.

Client-side:

  1. package main
  2. import (
  3. "fmt"
  4. "github.com/gogf/gf/v2/frame/g"
  5. "github.com/gogf/gf/v2/os/gctx"
  6. )
  7. func main() {
  8. var (
  9. ctx = gctx.New()
  10. client = g.Client()
  11. )
  12. client.SetPrefix("http://127.0.0.1:8199")
  13. for i := 0; i < 10; i++ {
  14. fmt.Println(client.PostContent(ctx, "/api/v1/user/info", `{"Path":"user/profile"}`))
  15. }
  16. }

Based on our understanding, after submission by the client, the server should receive the route parameter path as user/info. However, due to a program BUG, strangely, the client also submitted a JSON in the Body, with parameter name Path and parameter value user/profile. Now, which value will the server’s API object attribute Path hold?

Running the client repeatedly, the output results are all:

  1. {"code":0,"message":"","data":{"Path":"user/profile"}}
  2. {"code":0,"message":"","data":{"Path":"user/profile"}}
  3. {"code":0,"message":"","data":{"Path":"user/profile"}}
  4. {"code":0,"message":"","data":{"Path":"user/profile"}}
  5. {"code":0,"message":"","data":{"Path":"user/profile"}}
  6. {"code":0,"message":"","data":{"Path":"user/profile"}}
  7. {"code":0,"message":"","data":{"Path":"user/profile"}}
  8. {"code":0,"message":"","data":{"Path":"user/profile"}}
  9. {"code":0,"message":"","data":{"Path":"user/profile"}}
  10. {"code":0,"message":"","data":{"Path":"user/profile"}}

This means the parameters are all values submitted in Body, not the values from the route parameters. In fact, due to the case-sensitive nature of parameters, the server received two parameters at this time, one is the route parameter path, the other is the Path submitted in Body JSON. When converting to an API parameter object, the server uses the value from Body JSON since the attribute Path matches the Path in Body JSON more closely.

Documentation

📄️ Request - Complex ParametersIn applications built with the GoFrame framework, complex parameter transmission is achieved through Query or Form parameters. The document details the submission formats and server-side parsing methods for parameters with the same name, array parameters, and Map parameters, along with code examples. It is recommended to manage and maintain complex parameter transmission using JSON data encoding whenever possible.

📄️ Request - Parameter BindingThis document details how to handle request parameter binding in the GoFrame framework. By binding request parameters to struct objects, it facilitates structured parameter handling. The document introduces default and custom parameter binding rules, and how to perform convenient parameter binding and data validation through the Parse method of the Request object.

📄️ Request - ValidationIn the GoFrame framework, request input validation is implemented for struct attributes through the v tag. In the example, we explain how to use the gvalid module for validation, how to set and parse the registered request data structure, and how to handle validation errors. We also demonstrate how to test API responses and error messages using curl. Additionally, we provide usage suggestions for different versions to improve user experience and code usability.

📄️ Request - JSON/XMLGoFrame framework’s native support for JSON and XML data formats, detailing how to handle client-submitted data formats through the Request object of the GoFrame framework to improve development efficiency. The documentation includes sample code demonstrating how to parse and validate submitted data, as well as how to perform data format conversion, providing developers with convenient data acquisition and processing capabilities.

📄️ Request - Default ValueFunctionality in GoFrame framework to bind default values to request input object attributes using struct tags. It demonstrates, through examples, how to define parameter objects and set default values for their attributes, as well as how to process and validate request parameters on the server-side. It particularly emphasizes that default values will take effect when parameters are not submitted, but will be ignored when parameters are submitted (even if empty). Additionally, it provides some suggestions on default value parameter binding considerations.

📄️ Request - Custom ParametersSet and retrieve custom request parameters in the GoFrame framework. Custom variables have the highest priority and can override client-submitted parameters, making them suitable for variable sharing throughout the request process. This tutorial also provides real code examples demonstrating how to use the SetParam and GetParam methods within middleware to manage request parameters.

📄️ Request - ContextUsing the Context object in the GoFrame framework to handle context variable sharing in the request process. By providing necessary methods, developers can set custom variables at the beginning of a request and access them during subsequent processing. Additionally, this article includes example code and detailed steps on integrating third-party components to enhance functionality.

📄️ Request - File UploadingThe basic steps and methods for implementing file uploads in the GoFrame framework. With the information provided in the HTTPClient section, developers can gain a deeper understanding and mastery of how to handle file upload requests in applications to ensure effective management of file data in practical applications.