Home > Article > Backend Development > Set query parameters for HTTP requests using Golang
To set query parameters for HTTP requests in Go, you can use the http.Request.URL.Query().Set() method, which accepts query parameter names and values as parameters. Specific steps include: Create a new HTTP request. Set query parameters using the Query().Set() method. Encode the request. Execute the request. Get the value of a query parameter (optional). Remove query parameters (optional).
Setting query parameters for HTTP requests in Go is very simple. You just need to use the http.Request.URL.Query().Set()
method. This method accepts two parameters: the query parameter name and value to be set. For example, to set the page
query parameter to 3 for a request, you would use the following code:
func main() { client := &http.Client{} req, _ := http.NewRequest("GET", "http://example.com", nil) q := req.URL.Query() q.Set("page", "3") req.URL.RawQuery = q.Encode() resp, err := client.Do(req) if err != nil { log.Fatal(err) } defer resp.Body.Close() body, err := ioutil.ReadAll(resp.Body) if err != nil { log.Fatal(err) } fmt.Println(string(body)) }
The above code snippet creates a new HTTP request and then uses Query(). The Set()
method sets the page
query parameters. It then encodes the request and executes it using http.Client
.
Here are some other examples:
q.Add()
method. For example, to set the page
query parameter to 3 and the sort
query parameter to asc
, you would use the following code: q.Add("page", "3") q.Add("sort", "asc")
q.Get()
method. For example, to get the value of the page
query parameter, you can use the following code: page := q.Get("page")
q.Del()
method. For example, to remove the page
query parameter, you would use the following code: q.Del("page")
The above is the detailed content of Set query parameters for HTTP requests using Golang. For more information, please follow other related articles on the PHP Chinese website!