You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 
 

78 lines
1.7 KiB

package main
import (
"flag"
"html/template"
"io/ioutil"
"log"
"net/http"
"strings"
)
type serve struct {
feed *feed
token string
}
func (s *serve) rssHandler(w http.ResponseWriter, req *http.Request) {
log.Printf("Serve rss")
w.Write([]byte(s.feed.rss()))
}
func (s *serve) htmlHandler(w http.ResponseWriter, req *http.Request) {
log.Printf("Serve html")
items := s.feed.items()
index := template.Must(template.ParseFiles("index.html"))
if index == nil {
log.Printf("Error parsing template!")
return
}
index.Execute(w, items)
log.Printf("Rendered %v items", len(items))
}
func (s *serve) postHandler(w http.ResponseWriter, req *http.Request) {
if req.Method == "GET" {
log.Printf("GET...")
s.htmlHandler(w, req)
return
}
if req.Method != "POST" || !strings.Contains(req.URL.Path, s.token) {
log.Printf("Invalid request (%s): %v", req.Method, req.URL)
http.NotFound(w, req)
return
}
buff, err := ioutil.ReadAll(req.Body)
if err != nil {
log.Printf("Error reading body: %v", err)
return
}
err = s.feed.add(string(buff))
if err != nil {
log.Printf("Error adding entry to feed: %v", err)
} else {
log.Printf("Added url to the queue: %s", string(buff))
}
}
func main() {
dbPath := flag.String("db-path", "./feed.db", "the path to the database")
token := flag.String("token", "foobar", "token for authentication")
flag.Parse()
f, err := newFeed(*dbPath)
if err != nil {
log.Fatal(err)
}
defer f.close()
staticServer := http.FileServer(http.Dir("./static"))
s := serve{f, *token}
mux := http.NewServeMux()
mux.Handle("/static/", http.StripPrefix("/static", staticServer))
mux.HandleFunc("/rss", s.rssHandler)
mux.HandleFunc("/", s.postHandler)
log.Fatal(http.ListenAndServe(":2577", mux))
}