A response is more than its body. Before the body come the headers: lines of Name: value about the body, like the writing on an envelope around a letter. In Go, response.Header holds them, and response.Header.Get("Content-Type") reads one by its name. The header Content-Type says what kind of body this is: text/html for a web page, application/json for JSON.
Requests carry headers too, and you can add your own. http.Get builds a request and sends it in one go, so to add a header you build the request first with http.NewRequest, set the header on request.Header, then send it with http.DefaultClient.Do. The Accept header tells the server which kind of answer you want. After the call, response.Request.Header holds the headers your request carried. For example, to send an Accept-Language header that asks for French, and check that it went out:
request, _ := http.NewRequest("GET", supplier+"/catalog", nil)
request.Header.Set("Accept-Language", "fr")
reply, _ := http.DefaultClient.Do(request)
fmt.Println(reply.Request.Header.Get("Accept-Language"))
When you set no Accept header, Go sends none, which means any kind of body will do. Your script asks for two paths and prints what their headers say:
GET / → Content-Type: text/html; charset=utf-8 GET /prices (Accept: application/json) → Content-Type: application/json
Body: Supplier API. Try /prices Content-Type: text/html; charset=utf-8 Sent Accept: application/json Got Content-Type: application/json
Your task: the starting code asks for the home page and prints its body. Print its Content-Type. Then build a request for /prices with an Accept header for JSON, send it, and print the Accept header that went out and the Content-Type that came back.
Assignment
Follow the Coding Tutorial to read the Content-Type of two answers and send an Accept header of your own.
Hintresponse.Header holds the headers that came back; response.Request.Header the ones that went out. Read both with .Get and the header's name. The second answer goes into the response you already have, so use =, not :=.
Free plan: 30 tutor messages. PRO is unlimited.
