summaryrefslogtreecommitdiff
path: root/internal/findlinks/findlinks.go
blob: 00635ec22fbe915569e27bfaf6b41a82a8f4b488 (plain)
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
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
package findlinks

import (
	"fmt"
	"io"
	"strings"

	"golang.org/x/net/html"
	"golang.org/x/net/html/atom"
)

// A Link encapsulates the data harvested from a link.
type Link struct {
	Href string
	Text string
}

// findLinks consumes the given [io.Reader], scraping it of anchor
// tags. Each anchor tag is "unmarshalled" into a [Link]. The
// resulting slice of Links is returned, along with an error.
func FindLinks(r io.Reader) ([]Link, error) {
	doc, err := html.Parse(r)
	if err != nil {
		return nil, fmt.Errorf("can't parse html reader: %w", err)
	}

	links := iterHTML(doc, nil)

	return links, nil
}

func iterHTML(n *html.Node, buffer []Link) []Link {
	if n.Type == html.ElementNode && n.DataAtom == atom.A {
		var link Link

		// Href
		link.Href = extractHref(n)

		// Text
		chunks := extractText(n, nil)
		link.Text = strings.Join(chunks, " ")

		buffer = append(buffer, link)
	} else {
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			buffer = iterHTML(c, buffer)
		}
	}

	return buffer
}

// extractHref returns the first href attribute of anchor.
func extractHref(anchor *html.Node) string {
	var href string

	for _, a := range anchor.Attr {
		if a.Key == atom.Href.String() {
			href = a.Val
			break
		}
	}

	return href
}

// extractText recursively scans anchor to return the various nested
// pieces of text content.
func extractText(anchor *html.Node, buffer []string) []string {
	for c := anchor.FirstChild; c != nil; c = c.NextSibling {
		switch c.Type {
		case html.TextNode:
			buffer = append(buffer, c.Data)
		case html.ElementNode:
			buffer = extractText(c, buffer)
		}
	}

	return buffer
}