From 8606fdf632ca74102e6b49b9331f8f94bf9cb7b2 Mon Sep 17 00:00:00 2001 From: Mikolaj Date: Wed, 21 Nov 2018 20:31:05 +0100 Subject: [PATCH] go --- gotut.go | 62 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 62 insertions(+) create mode 100755 gotut.go diff --git a/gotut.go b/gotut.go new file mode 100755 index 0000000..28527cb --- /dev/null +++ b/gotut.go @@ -0,0 +1,62 @@ +package main + +import ( + "encoding/xml" + "fmt" + "html/template" + "io/ioutil" + "net/http" +) + +type NewsMap struct { + Keyword string + Location string +} + +type NewsAggPage struct { + Title string + News map[string]NewsMap +} + +type Sitemapindex struct { + Locations []string `xml:"sitemap>loc"` +} + +type News struct { + Titles []string `xml:"url>news>title"` + Keywords []string `xml:"url>news>keywords"` + Locations []string `xml:"url>loc"` +} + +func indexHandler(w http.ResponseWriter, r *http.Request) { + fmt.Fprintf(w, "

Whoa, Go is neat!

") +} + +func newsAggHandler(w http.ResponseWriter, r *http.Request) { + var s Sitemapindex + var n News + resp, _ := http.Get("https://www.washingtonpost.com/news-sitemap-index.xml") + bytes, _ := ioutil.ReadAll(resp.Body) + xml.Unmarshal(bytes, &s) + news_map := make(map[string]NewsMap) + + for _, Location := range s.Locations { + resp, _ := http.Get(Location) + bytes, _ := ioutil.ReadAll(resp.Body) + xml.Unmarshal(bytes, &n) + + for idx, _ := range n.Keywords { + news_map[n.Titles[idx]] = NewsMap{n.Keywords[idx], n.Locations[idx]} + } + } + + p := NewsAggPage{Title: "Amazing News Aggregator", News: news_map} + t, _ := template.ParseFiles("newsaggtemplate.html") + t.Execute(w, p) +} + +func main() { + //http.HandleFunc("/", indexHandler) + http.HandleFunc("/", newsAggHandler) + http.ListenAndServe(":8000", nil) +}