Sending HTTP GET requests with parameters in Go is straightforward thanks to the net/http package, which is a part of the Go standard library. In this article, we will explore how to build a simple HTTP GET request and add query parameters to it.
Step 1: Setting Up Your Go Project
First, create a new directory for your Go project and initialize a Go module:
mkdir my-go-get-request
cd my-go-get-request
go mod init my-go-get-requestStep 2: Importing Required Packages
In your main Go file, you need to import the necessary packages:
package main
import (
"fmt"
"net/http"
"net/url"
"io/ioutil"
"log"
)Step 3: Create a HTTP Client
A HTTP client is required to make requests:
func main() {
client := &http.Client{}
// Construct request
baseUrl := "http://example.com/api"
// Setup query parameters
endpoint, err := url.Parse(baseUrl)
if err != nil {
log.Fatal(err)
}
queryParams := url.Values{}
queryParams.Set("param1", "value1")
queryParams.Set("param2", "value2")
endpoint.RawQuery = queryParams.Encode()Step 4: Sending GET Request
Now that you have set up your request and parameters, you can send the GET request and handle the response:
// Create request with merged query params
req, err := http.NewRequest("GET", endpoint.String(), nil)
if err != nil {
log.Fatal(err)
}
// Execute request
resp, err := client.Do(req)
if err != nil {
log.Fatal(err)
}
defer resp.Body.Close()Step 5: Reading and Handling the Response
Reading the contents of the server's response can inform us whether our request was successful:
// Read response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
log.Fatal(err)
}
fmt.Println(string(body))
}Conclusion
You now have a basic Go application that sends HTTP GET requests with parameters. This is an important skill for accessing RESTful APIs and integrating services in Go. Make sure to properly handle any errors and incorporate logging as needed for production-ready applications.