Start learning free

LESSON 1 OF 173 · BACKEND: HOW THE WEB WORKS

Your First Request

Practice

Every time a browser opens a page, it sends a request to a server, a program waiting on some computer, and the server sends back a response. A Go program can do the same with the net/http package.

http.Get(address) sends the request and returns the response (and an error, which you can skip with _). A response starts with a status code, a number that says how it went (200 means OK), and then comes the body, the content itself. .StatusCode gives the number. .Body is a stream: io.ReadAll reads it into bytes, and string(...) turns them into text. defer closes the body when the function ends.

page, _ := http.Get("https://example.com/about")
defer page.Body.Close()
fmt.Println(page.StatusCode)
content, _ := io.ReadAll(page.Body)
fmt.Println(string(content))

The shop's supplier runs a server at the address in supplier. Its home page is the path /. When your program asks for it, it must print:

Status: 200
Text: Supplier API. Try /prices

Your task: inside main, send a GET request to the supplier's home page, keep the answer in response and close its body with defer, then print its status code and its body as text, each after its label.


Assignment
Follow the Coding Tutorial to send your first request and print the status code and the text that come back.


Hint
The address is a string: join supplier and the path with +. fmt.Println can take a label and a value, separated by a comma. Read the body with io.ReadAll and print it with string(body).


STEP 1 OF 3
    Ctrl + Enter to check