Last active
August 29, 2015 14:06
-
-
Save Sancus/f4670506b1ec2335ba4d 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 ( | |
"encoding/json" | |
"fmt" | |
"github.com/PuerkitoBio/goquery" | |
"net/http" | |
) | |
type PageData struct { | |
Title string | |
err string | |
} | |
func main() { | |
http.HandleFunc("/", handler) | |
http.ListenAndServe(":8000", nil) | |
} | |
func httpget(url string) PageData { | |
var pd PageData | |
response, err := http.Get(url) | |
if err != nil { | |
pd.err = fmt.Sprintf("%s", err) | |
} else { | |
pd.Title = parseTitle(response) | |
} | |
return pd | |
} | |
func handler(w http.ResponseWriter, r *http.Request) { | |
url := r.FormValue("url") | |
var pd PageData = httpget(url) | |
json_out, err := json.Marshal(pd) | |
if err != nil { | |
fmt.Fprintf(w, "{\"Err\":\"%s\"}", err) | |
} | |
fmt.Fprintf(w, "%s", json_out) | |
} | |
func parseTitle(r *http.Response) string { | |
doc, err := goquery.NewDocumentFromResponse(r) | |
if err != nil { | |
return fmt.Sprintf("%s", err) | |
} | |
title := doc.Find("title").Text() | |
return title | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment