Skip to content

Golang HTTP Request Header Example

Golang is very good at making and responding to requests 🙂 Request struct has a Header type that implements this Set method:

req.Header.Set("Accept", "application/json")

A working example is:

package main

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

func main() {
	url := "https://www.code-paste.com/"

	req, err := http.NewRequest(http.MethodGet, url, nil)
	if err != nil {
		log.Fatalf("failed to : %s", err)
	}

	req.Header.Set("Accept", "application/json")

	client := &http.Client{}
	resp, err := client.Do(req)
	if err != nil {
		log.Fatalf("failed to : %s", err)
	}

	defer resp.Body.Close()

	b, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		log.Fatalln(err)
	}

	fmt.Println(string(b))
}

Leave a Reply

Your email address will not be published. Required fields are marked *