ch5: add findlinks1 to test external dependencies

This commit is contained in:
Alan Donovan 2015-09-24 09:32:47 -04:00
parent 49db6169b1
commit 27564a3784
1 changed files with 73 additions and 0 deletions

73
ch5/findlinks1/main.go Normal file
View File

@ -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
*/