Making HTTP GET Requests in Go
Introduction:
In modern web development, interacting with external APIs is a common task. In Go, the net/http package provides a robust way to perform HTTP requests. In this tutorial, we'll explore how to create a simple Go program to make an HTTP GET request to an API endpoint.
Prerequisites:
Code Explanation:
Package Imports:
package main
import (
"fmt"
"io/ioutil"
"net/http"
)
Main Function:
func main() {
// Replace 'YOUR_BEARER_TOKEN' with your actual bearer token
bearerToken := "YOUR_BEARER_TOKEN"
apiURL := "https://api.example.com/endpoint" // Replace with the API endpoint you want to call
Creating HTTP Request:
req, err := http.NewRequest("GET", apiURL, nil)
if err != nil {
fmt.Println("Error creating HTTP request:", err)
return
}
Setting Authorization Header:
领英推荐
req.Header.Set("Authorization", "Bearer "+bearerToken)
Sending HTTP Request:
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
fmt.Println("Error sending HTTP request:", err)
return
}
defer resp.Body.Close()
Reading Response Body:
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
fmt.Println("Error reading response body:", err)
return
}
Printing Response:
fmt.Println("Response:", string(body))
}
Conclusion:
In this tutorial, we've demonstrated how to make an HTTP GET request in Go using the net/http package. This code structure can be utilized to interact with various APIs by modifying the request parameters and endpoints. Remember to replace placeholders like YOUR_BEARER_TOKEN and api.example.com with actual values before executing the code.
This example serves as a starting point for integrating HTTP requests into your Go applications, enabling communication with external services or APIs efficiently.