-
Notifications
You must be signed in to change notification settings - Fork 0
Commit
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.
- Loading branch information
0 parents
commit da2fe99
Showing
3 changed files
with
54 additions
and
0 deletions.
There are no files selected for viewing
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1 @@ | ||
webby |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,3 @@ | ||
# Webby Bot | ||
Webby is an IRC bot written in Go. The initial goal is to provide helpers for | ||
parsing URLs to provide the URL title and a shortend URL. |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Original file line number | Diff line number | Diff line change |
---|---|---|
@@ -0,0 +1,50 @@ | ||
package main | ||
|
||
import ( | ||
"io" | ||
"net/http" | ||
|
||
"golang.org/x/net/html" | ||
) | ||
|
||
func isTitleElement(n *html.Node) bool { | ||
return n.Type == html.ElementNode && n.Data == "title" | ||
} | ||
|
||
func traverse(n *html.Node) (string, bool) { | ||
if isTitleElement(n) { | ||
return n.FirstChild.Data, true | ||
} | ||
|
||
for c := n.FirstChild; c != nil; c = c.NextSibling { | ||
result, ok := traverse(c) | ||
if ok { | ||
return result, ok | ||
} | ||
} | ||
return "", false | ||
} | ||
|
||
func GetHtmlTitle(r io.Reader) (string, bool) { | ||
doc, docErr := html.Parse(r) | ||
if docErr != nil { | ||
panic("Failed to parse url") | ||
} | ||
|
||
return traverse(doc) | ||
} | ||
|
||
func main() { | ||
url := "http://google.com" | ||
resp, getErr := http.Get(url) | ||
if getErr != nil { | ||
panic(getErr) | ||
} | ||
defer resp.Body.Close() | ||
|
||
if title, ok := GetHtmlTitle(resp.Body); ok { | ||
println(title) | ||
} else { | ||
println("No title found") | ||
} | ||
} |