6. net http

In this course, we'll be using Go's standard net/httparrow-up-right package and the http.Clientarrow-up-right to make HTTP requests. In fact, we've already been using it! The http.Getarrow-up-right function uses the http.DefaultClientarrow-up-right under the hood.

Making a Request

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

func getProjects() ([]byte, error) {
	res, err := http.Get("https://api.jello.com/projects")
	if err != nil {
		return nil, fmt.Errorf("error making request: %w", err)
	}
	defer res.Body.Close()

	data, err := io.ReadAll(res.Body)
	if err != nil {
		return nil, fmt.Errorf("error reading response: %w", err)
	}
	return data, nil
}

We'll go in-depth on the various things happening here later, but let's cover some basics for now.

  • http.Get uses the http.DefaultClient to make a request to the given url

  • res is the HTTP response that comes back from the server

  • defer res.Body.Close() ensures that the response body is properly closed after reading. Not doing so can cause memory issues.

  • io.ReadAll reads the response body into a slice of bytes []byte called data

Assignment

There is a bug in the getIssueData function! It's returning the entire http.Responsearrow-up-right instead of the data from the body (a slice of bytes). Fix it so that it returns []byte.

1

Use io.ReadAll to read the .Body of the response

Read the response body into a byte slice using io.ReadAll(res.Body).

2

Return the resulting []byte

Return the []byte result (and handle any read errors).

Solution