-
Notifications
You must be signed in to change notification settings - Fork 9
/
Copy pathfindlinks.go
58 lines (52 loc) · 1.1 KB
/
findlinks.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
package main
import (
"fmt"
"log"
"net/http"
"golang.org/x/net/html"
)
func main() {
http.HandleFunc("/", handler)
log.Fatal(http.ListenAndServe("0.0.0.0:8000", nil))
}
func handler(w http.ResponseWriter, r *http.Request) {
url := r.URL.Query().Get("q")
fmt.Fprintf(w, "Page = %q\n", url)
if len(url) == 0 {
return
}
page, err := parse("https://" + url)
if err != nil {
fmt.Printf("Error getting page %s %s\n", url, err)
return
}
links := pageLinks(nil, page)
for _, link := range links {
fmt.Fprintf(w, "Link = %q\n", link)
}
}
func parse(url string) (*html.Node, error) {
fmt.Println(url)
r, err := http.Get(url)
if err != nil {
return nil, fmt.Errorf("Cannot get page")
}
b, err := html.Parse(r.Body)
if err != nil {
return nil, fmt.Errorf("Cannot parse page")
}
return b, err
}
func pageLinks(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 = pageLinks(links, c)
}
return links
}