5.8 Deferred Function Calls
Our findLinks
examples used the output of http.Get
as the input to html.Parse
.
This works well if the content of the requested URL is indeed HTML,
but many pages contain images, plain text, and other file formats.
Feeding such files into an HTML parser could have undesirable
effects.
The program below fetches an HTML document and prints its title.
The title
function inspects the Content-Type
header of
the server’s response and returns an error if the document is not
HTML.
func title(url string) error { resp, err := http.Get(url) if err != nil { return err } // Check Content-Type is HTML (e.g., "text/html; charset=utf-8"). ct := resp.Header.Get("Content-Type") if ...
Get The Go Programming Language now with the O’Reilly learning platform.
O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.