How to Perform GET Requests with Query Strings in Go
Building GET requests with dynamic query strings in Go can be tricky for beginners. In this article, we'll explore a simple yet effective approach to achieve this task.
Consider the following scenario: you need to make a GET request to an API endpoint that requires an "api_key" query parameter. Hardcoding the API key into the request URL is not ideal, as it limits flexibility and security.
To overcome this challenge, we can leverage Go's net/url package. This package provides the url.Values type, which allows us to manipulate query parameters dynamically.
Here's how we can modify our sample script to build and encode a query string:
package main import ( "fmt" "log" "net/http" "os" "url" ) func main() { req, err := http.NewRequest("GET", "http://api.themoviedb.org/3/tv/popular", nil) if err != nil { log.Print(err) os.Exit(1) } q := req.URL.Query() q.Add("api_key", "KEY_FROM_ENV_OR_FLAG") q.Add("another_thing", "foo & bar") req.URL.RawQuery = q.Encode() fmt.Println(req.URL.String()) }
In this example:
This approach allows us to dynamically build and encode query strings, maintaining flexibility and security by separating the API key from the request URL.
The above is the detailed content of How to Dynamically Build GET Requests with Query Strings in Go?. For more information, please follow other related articles on the PHP Chinese website!