Skip to content

Instantly share code, notes, and snippets.

@BoredHackerBlog
Created May 17, 2020 19:22
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save BoredHackerBlog/1a30ac3504626788a53130ca23e8ccb7 to your computer and use it in GitHub Desktop.
Save BoredHackerBlog/1a30ac3504626788a53130ca23e8ccb7 to your computer and use it in GitHub Desktop.
package main
import (
"fmt"
"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, err := html.Parse(r)
if err != nil {
panic("Fail to parse html")
}
return traverse(doc)
}
func main() {
resp, _ := http.Get("google.com")
defer resp.Body.Close()
title, _ := GetHtmlTitle(resp.Body)
fmt.Println(title)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment