開発環境
- macOS Mojave - Apple (OS)
- Emacs (Text Editor)
- Windows 10 Pro (OS)
- Visual Studio Code (Text Editor)
- Go (プログラミング言語)
プログラミング言語Go (ADDISON-WESLEY PROFESSIONAL COMPUTING SERIES) (Alan A.A. Donovan(著)、Brian W. Kernighan(著)、柴田 芳樹(翻訳)、丸善出版)の第5章(関数)、5.2(再帰)、練習問題5.4の解答を求めてみる。
コード
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, "findlinks: %v\n", err) os.Exit(1) } links := make(map[string][]string) for k, ls := range visit(links, doc) { fmt.Println(k) for _, l := range ls { fmt.Println(l) } } } func visit(links map[string][]string, n *html.Node) map[string][]string { if n == nil { return links } if n.Type == html.ElementNode { if n.Data == "img" { for _, a := range n.Attr { if a.Key == "src" { links["img"] = append(links["imag"], a.Val) } } } else if n.Data == "script" { for _, a := range n.Attr { if a.Key == "src" { links["script"] = append(links["script"], a.Val) } } } else if n.Data == "link" { for _, a := range n.Attr { if a.Key == "href" { links["link"] = append(links["link"], a.Val) } } } } links = visit(links, n.FirstChild) links = visit(links, n.NextSibling) return links }
入出力結果(cmd(コマンドプロンプト)、Terminal)
$ ./fetch https://golang.org | go run sample4.go script /lib/godoc/jquery.js /lib/godoc/playground.js /lib/godoc/godocs.js link /lib/godoc/style.css /opensearch.xml $ ./fetch https://example.com | go run sample4.go $ ./fetch https://www.iana.org/domains/reserved | go run sample4.go link /_css/2015.1/screen.css /_css/2015.1/print.css /_img/bookmark_icon.ico script /_js/2013.1/jquery.js /_js/2013.1/iana.js img /_img/2013.1/iana-logo-header.svg $
0 コメント:
コメントを投稿