Executing HTTP requests in golang can be used to create an api integration and automate workflows. The standard library “net/http” package can be used to create a request object and the DefaultClient can be used to execute the request. We can expand this basic example to create complex interactions between backend services communicating over HTTP APIs.

Playground: https://go.dev/play/p/AGV2OyqN-a6

package main

import (
	"io"
	"net/http"
)

func main() {
	// create a new request
	req, err := http.NewRequest(http.MethodGet, "https://jsonplaceholder.typicode.com/todos/1", nil)
	if err != nil {
		panic(err)
	}

	// add a header to the request
	req.Header.Add("Accept", "application/json")

	// make the request using the default client
	resp, err := http.DefaultClient.Do(req)
	if err != nil {
		panic(err)
	}
	// make sure to close the response body after we are done with it
	defer resp.Body.Close()

	// print the response status code
	println("STATUS CODE:", resp.StatusCode)
	println("STATUS TEXT:", "\""+resp.Status+"\"")
	println("HEADERS:")

	// print the response headers
	for key, values := range resp.Header {
		for _, value := range values {
			println("  ", key+":", value)
		}
	}
	// read the response body into a byte slice
	body, err := io.ReadAll(resp.Body)
	if err != nil {
		panic(err)
	}
	// print the response body
	println("BODY:")
	println(string(body))
}