Skip to content

Instantly share code, notes, and snippets.

@EtienneR
Last active August 29, 2015 14:27
Show Gist options
  • Save EtienneR/91d67a9d53e5f3923d2e to your computer and use it in GitHub Desktop.
Save EtienneR/91d67a9d53e5f3923d2e to your computer and use it in GitHub Desktop.
RSS feed part4 (webserver)
package main
import (
"encoding/xml"
"net/http"
)
func main() {
http.HandleFunc("/", rssHandler)
http.ListenAndServe(":3000", nil)
}
func rssHandler(w http.ResponseWriter, r *http.Request) {
type Item struct {
Title string `xml:"title"`
Link string `xml:"link"`
Description string `xml:"description"`
}
type rss struct {
Version string `xml:"version,attr"`
Description string `xml:"channel>description"`
Link string `xml:"channel>link"`
Title string `xml:"channel>title"`
Item []Item `xml:"channel>item"`
}
articles := []Item{
{"foo", "http://mywebsite.com/foo", "lorem ipsum"},
{"foo2", "http://mywebsite.com/foo2", "lorem ipsum2"}},
feed := &rss{
Version: "2.0",
Description: "My super website",
Link: "http://mywebsite.com",
Title: "Mywebsite",
Item: articles,
}
x, err := xml.MarshalIndent(feed, "", " ")
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Header().Set("Content-Type", "application/xml")
w.Write(x)
}
HTTP/1.1 200 OK
Content-Type: application/xml
<rss version="2.0">
<channel>
<description>My super website</description>
<link>http://mywebsite.com</link>
<title>Mywebsite</title>
<item>
<title>foo</title>
<link>http://mywebsite.com/foo</link>
<description>lorem ipsum</description>
</item>
<item>
<title>foo2</title>
<link>http://mywebsite.com/foo2</link>
<description>lorem ipsum2</description>
</item>
</channel>
</rss>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment