Skip to content

Commit da2fe99

Browse files
committed
Title parsing
0 parents  commit da2fe99

3 files changed

Lines changed: 54 additions & 0 deletions

File tree

‎.gitignore‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1 @@
1+
webby

‎README.md‎

Lines changed: 3 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,3 @@
1+
# Webby Bot
2+
Webby is an IRC bot written in Go. The initial goal is to provide helpers for
3+
parsing URLs to provide the URL title and a shortend URL.

‎main.go‎

Lines changed: 50 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,50 @@
1+
package main
2+
3+
import (
4+
"io"
5+
"net/http"
6+
7+
"golang.org/x/net/html"
8+
)
9+
10+
func isTitleElement(n *html.Node) bool {
11+
return n.Type == html.ElementNode && n.Data == "title"
12+
}
13+
14+
func traverse(n *html.Node) (string, bool) {
15+
if isTitleElement(n) {
16+
return n.FirstChild.Data, true
17+
}
18+
19+
for c := n.FirstChild; c != nil; c = c.NextSibling {
20+
result, ok := traverse(c)
21+
if ok {
22+
return result, ok
23+
}
24+
}
25+
return "", false
26+
}
27+
28+
func GetHtmlTitle(r io.Reader) (string, bool) {
29+
doc, docErr := html.Parse(r)
30+
if docErr != nil {
31+
panic("Failed to parse url")
32+
}
33+
34+
return traverse(doc)
35+
}
36+
37+
func main() {
38+
url := "http://google.com"
39+
resp, getErr := http.Get(url)
40+
if getErr != nil {
41+
panic(getErr)
42+
}
43+
defer resp.Body.Close()
44+
45+
if title, ok := GetHtmlTitle(resp.Body); ok {
46+
println(title)
47+
} else {
48+
println("No title found")
49+
}
50+
}

0 commit comments

Comments
 (0)