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.
feed/main.go

94 lines
2.1 KiB

3 years ago
package main
import (
"flag"
3 years ago
"html/template"
3 years ago
"log"
"net/http"
"strings"
"github.com/jamiealquiza/envy"
3 years ago
)
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()))
}
3 years ago
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"))
3 years ago
if index == nil {
log.Printf("Error parsing template!")
return
}
3 years ago
index.Execute(w, items)
log.Printf("Rendered %v items", len(items))
}
3 years ago
func (s *serve) postHandler(w http.ResponseWriter, req *http.Request) {
if req.URL.Path == "/" {
3 years ago
log.Printf("GET...")
3 years ago
s.htmlHandler(w, req)
return
}
if !strings.Contains(req.URL.Path, s.token) {
3 years ago
log.Printf("Invalid request (%s): %v", req.Method, req.URL)
http.NotFound(w, req)
return
}
req.ParseForm()
urls, ok := req.Form["url"]
if !ok || len(urls) < 1 {
log.Printf("Not valid urls: %v", req.URL)
3 years ago
return
}
for _, url := range urls {
err := s.feed.add(url)
if err != nil {
log.Printf("Error adding to feed: %v", err)
} else {
log.Printf("Added url to the queue: %s", url)
}
3 years ago
}
}
func main() {
dbPath := flag.String("db-path", "./feed.db", "the path to the database")
token := flag.String("token", "foobar", "token for authentication")
customerKey := flag.String("customer-key", "", "pocket customer key")
accessToken := flag.String("access-token", "", "pocket access token")
envy.Parse("FEED")
3 years ago
flag.Parse()
var fetcher contentFetcher
if *accessToken != "" && *customerKey != "" {
fetcher = newPocket(*customerKey, *accessToken)
} else {
fetcher = &dummyContentFetcher{}
}
f, err := newFeed(*dbPath, fetcher)
3 years ago
if err != nil {
log.Fatal(err)
}
defer f.close()
3 years ago
staticServer := http.FileServer(http.Dir("./static"))
3 years ago
s := serve{f, *token}
mux := http.NewServeMux()
3 years ago
mux.Handle("/static/", http.StripPrefix("/static", staticServer))
3 years ago
mux.HandleFunc("/rss", s.rssHandler)
mux.HandleFunc("/", s.postHandler)
log.Fatal(http.ListenAndServe(":2577", mux))
}