How to send requests to Web API using Go's net/http


This post is written 26 months ago. Probably the information might be out of date.

The simplest way

When it is a simple request, you can use http.Get.

foo.js
func main() {
	url := "https://api.chucknorris.io/jokes/random"

	res, err := http.Get(url)

	if err != nil {
		fmt.Println(err)
	}

  	defer res.Body.Close()

  	ResBodybyteArray, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(ResBodybyteArray))
}
copied!

When you need to set params or Header

When you have to set params, we can add as described below.

foo.js
func main() {
	url := "https://itunes.apple.com/search"

	req, _ := http.NewRequest("GET", url, nil)
	params := req.URL.Query()
	params.Add("term", "beatles")
	params.Add("country", "jp")
	req.URL.RawQuery = params.Encode()
	client := new(http.Client)
	res, _ := client.Do(req)

	byteArray, _ := ioutil.ReadAll(res.Body)
  	fmt.Println(string(byteArray))
}
copied!

When Header is required, we can add like ↓

req.Header.Set("name", "value")
copied!

If you want more details of http.Client, you can find infomations in the section of Client on the document.

https://pkg.go.dev/net/http#Client
buy me a coffee