summaryrefslogtreecommitdiff
path: root/href.go
blob: 811a96395fd76f468f59d392c2ba6c4683f21b15 (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
package main

import (
	"net/http"
	"strings"

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

var cache = make(map[string]string)

func findTitle(n *html.Node) (s string) {
	if n.Type == html.ElementNode && n.Data == "title" {
		for c := n.FirstChild; c != nil; c = c.NextSibling {
			s += c.Data
		}
		return strings.TrimSpace(s)
	}
	for c := n.FirstChild; c != nil; c = c.NextSibling {
		if t := findTitle(c); t != "" {
			return t
		}
	}
	return ""
}

func FetchTitle(url string) (string, error) {
	if title, ok := cache[url]; ok {
		return title, nil
	}

	resp, err := http.Get(url)
	if err != nil {
		return "", err
	}
	defer resp.Body.Close()

	doc, err := html.Parse(resp.Body)
	if err != nil {
		return "", err
	}

	title := findTitle(doc)
	cache[url] = title

	return title, nil
}