From 27564a37845ffbb83ad1e73df8086fab5e6c834b Mon Sep 17 00:00:00 2001 From: Alan Donovan Date: Thu, 24 Sep 2015 09:32:47 -0400 Subject: [PATCH] ch5: add findlinks1 to test external dependencies --- ch5/findlinks1/main.go | 73 ++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 73 insertions(+) create mode 100644 ch5/findlinks1/main.go diff --git a/ch5/findlinks1/main.go b/ch5/findlinks1/main.go new file mode 100644 index 0000000..bfae904 --- /dev/null +++ b/ch5/findlinks1/main.go @@ -0,0 +1,73 @@ +// Copyright © 2016 Alan A. A. Donovan & Brian W. Kernighan. +//!+main + +// Findlinks1 prints the links in an HTML document read from standard input. +package main + +import ( + "fmt" + "os" + + "golang.org/x/net/html" +) + +func main() { + doc, err := html.Parse(os.Stdin) + if err != nil { + fmt.Fprintf(os.Stderr, "findlinks1: %v\n", err) + os.Exit(1) + } + for _, link := range visit(nil, doc) { + fmt.Println(link) + } +} + +//!-main + +//!+visit +// visit appends to links each link found in n and returns the result. +func visit(links []string, n *html.Node) []string { + if n.Type == html.ElementNode && n.Data == "a" { + for _, a := range n.Attr { + if a.Key == "href" { + links = append(links, a.Val) + } + } + } + for c := n.FirstChild; c != nil; c = c.NextSibling { + links = visit(links, c) + } + return links +} + +//!-visit + +/* +//!+html +package html + +type Node struct { + Type NodeType + Data string + Attr []Attribute + FirstChild, NextSibling *Node +} + +type NodeType int32 + +const ( + ErrorNode NodeType = iota + TextNode + DocumentNode + ElementNode + CommentNode + DoctypeNode +) + +type Attribute struct { + Key, Val string +} + +func Parse(r io.Reader) (*Node, error) +//!-html +*/