morning-coffee/routes.go

94 lines
1.8 KiB
Go
Raw Permalink Normal View History

package main
import (
"encoding/json"
"fmt"
"net/http"
"net/url"
"slices"
"time"
)
type Link struct {
Url string `json:"url"`
PublishedDate time.Time `json:"publishedDate"`
Title string `json:"title"`
}
func (l Link) GetLocalizedPublishedDate(loc string) time.Time {
if loc == "" {
loc = "America/New_York"
}
location, _ := time.LoadLocation(loc)
return l.PublishedDate.In(location)
}
// Healthcheck route
//
// Confirms that the app is alive without guarantees
// about it being fully-functional.
func healthcheck(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
}
// About page
//
// Static content for the about page.
func about(w http.ResponseWriter, r *http.Request) {
2024-09-21 04:50:10 +00:00
Render(w, "about", nil)
}
// Feeds list
//
// Lists all feed elements in store.
func listContent(w http.ResponseWriter, r *http.Request) {
links := []Link{}
for _, feed := range SharedCache.List("feeds") {
var formattedItems []Link
json.Unmarshal([]byte(feed), &formattedItems)
links = append(links, formattedItems...)
}
slices.SortStableFunc(links, func(a Link, b Link) int {
if a.PublishedDate.After(b.PublishedDate) {
return -1
}
return 1
})
2024-09-21 04:50:10 +00:00
Render(w, "index", links)
}
// Manage content
//
// Interface to add new feed subscriptions and get a list
// of current subs.
func manageContent(w http.ResponseWriter, r *http.Request) {
if r.Method == "POST" {
r.ParseForm()
urlValue := r.PostFormValue("url")
if _, err := url.Parse(urlValue); err != nil {
w.WriteHeader(400)
return
}
cacheKey := fmt.Sprintf("feedurl:%s", urlValue)
SharedCache.Set(cacheKey, urlValue)
go fetchFeed(urlValue)
w.WriteHeader(201)
}
allFeeds := SharedCache.List("feedurl")
type ManageTmplData struct {
Feeds map[string]string
}
2024-09-21 04:50:10 +00:00
Render(w, "manage", ManageTmplData{Feeds: allFeeds})
}