Golang has an inbuilt package called “net/http” using which we can send the HTTP to APIs easily along with the custom headers.

Import the package & create HTTP client

To get started, first, import the required packages i.e. net/http and then we need to create the HTTP client which will be used to send the request. We can make different types of requests such as GET, POST etc, using the HTTP client.

package main

import (
	"fmt"
	"net/http"
)

client := &http.Client{}

Create an HTTP request and set the custom headers

Now, create an HTTP request using the respective HTTP method, URL, and payload if needed.

By using the “Header” field of the request object we can include the custom headers in the request.

url := "https://example.com/api"
req, err := http.NewRequest("GET", url, nil)
if err != nil {
    fmt.Println("Error creating request:", err)
    return
}

req.Header.Set("Content-Type", "application/json")
req.Header.Set("Authorization", "Bearer <token>")

Send the request

Finally, send the request using the HTTP client’s “Do” method and handle the response from the server.

resp, err := client.Do(req)
if err != nil {
    fmt.Println("Error sending request:", err)
    return
}

defer resp.Body.Close()

Handle the response

// Read the response body
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
	fmt.Println("Error reading response:", err)
	return
}

Following is the complete example:

package main

import (
	"fmt"
	"net/http"
	"io/ioutil"
)

func main() {
	// Create an HTTP client
	client := &http.Client{}

	// Create an HTTP request
	url := "https://api.example.com/users"
	req, err := http.NewRequest("GET", url, nil)
	if err != nil {
		fmt.Println("Error creating request:", err)
		return
	}

	// Set custom headers
	req.Header.Set("Content-Type", "application/json")
	req.Header.Set("Authorization", "Bearer <token>")

	// Send the request
	resp, err := client.Do(req)
	if err != nil {
		fmt.Println("Error sending request:", err)
		return
	}

	defer resp.Body.Close()

	// Read the response body
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		fmt.Println("Error reading response:", err)
		return
	}

	// Print the response status code and body
	fmt.Println("Response Status:", resp.Status)
	fmt.Println("Response Body:", string(body))
}

Categorized in:

Tagged in: