MCPcopy
hub / github.com/adonovan/gopl.io / title

Function title

ch5/title2/title.go:33–62  ·  view source on GitHub ↗

!+

(url string)

Source from the content-addressed store, hash-verified

31
32//!+
33func title(url string) error {
34 resp, err := http.Get(url)
35 if err != nil {
36 return err
37 }
38 defer resp.Body.Close()
39
40 ct := resp.Header.Get("Content-Type")
41 if ct != "text/html" && !strings.HasPrefix(ct, "text/html;") {
42 return fmt.Errorf("%s has type %s, not text/html", url, ct)
43 }
44
45 doc, err := html.Parse(resp.Body)
46 if err != nil {
47 return fmt.Errorf("parsing %s as HTML: %v", url, err)
48 }
49
50 // ...print doc's title element...
51 //!-
52 visitNode := func(n *html.Node) {
53 if n.Type == html.ElementNode && n.Data == "title" &&
54 n.FirstChild != nil {
55 fmt.Println(n.FirstChild.Data)
56 }
57 }
58 forEachNode(doc, visitNode, nil)
59 //!+
60
61 return nil
62}
63
64//!-
65

Callers 1

mainFunction · 0.70

Calls 3

forEachNodeFunction · 0.70
GetMethod · 0.65
CloseMethod · 0.45

Tested by

no test coverage detected