Created
May 17, 2020 19:22
-
-
Save BoredHackerBlog/1a30ac3504626788a53130ca23e8ccb7 to your computer and use it in GitHub Desktop.
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
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