Files
crowsnest/cmd/frontend/main.go
2025-01-02 00:35:41 +01:00

76 lines
2.0 KiB
Go

package main
import (
//"fmt"
"crowsnest/internal/data"
"crowsnest/internal/model"
"fmt"
"html/template"
"net/http"
"strings"
)
type articleDateOrder struct {}
func (ord articleDateOrder) Weight(a *model.Article) int {
return int(a.PublishDate.Unix())
}
type articleTermFrequency struct {
terms []string
}
func (ord articleTermFrequency) Weight(a *model.Article) int {
score := 0
for _, term := range ord.terms {
term = strings.TrimSpace(term)
if term == "" { continue }
score += strings.Count(a.Content, term)
}
return score
}
func index(w http.ResponseWriter, req *http.Request) {
fds, _ := data.NewFileDatastore("./persistence/spiegel100.json")
repo, _ := data.NewDefaultRepository[*model.Article](fds, "article")
articles, _ := repo.GetByCriteria(articleDateOrder{})
t := template.Must(template.ParseFiles("templates/article.html", "templates/layout.html"))
_ = t.ExecuteTemplate(w, "base", articles[:10])
}
func search(w http.ResponseWriter, req *http.Request) {
// Parse the form data
err := req.ParseForm()
if err != nil {
http.Error(w, "Unable to parse form", http.StatusBadRequest)
return
}
searchTerms := strings.Split(req.FormValue("search"), " ")
fds, _ := data.NewFileDatastore("./persistence/spiegel100.json")
repo, _ := data.NewDefaultRepository[*model.Article](fds, "article")
articles, _ := repo.GetByCriteria(articleTermFrequency{ terms: searchTerms })
t := template.Must(template.ParseFiles("templates/article.html", "templates/layout.html"))
_ = t.ExecuteTemplate(w, "base", articles)
}
func main() {
// routes
http.HandleFunc("/", index)
http.HandleFunc("/search", search)
// serve files from the "static" directory
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static", http.StripPrefix("/", fs))
t := template.Must(template.ParseFiles("templates/article.html"))
fmt.Println(t)
// start server
http.ListenAndServe(":8080", nil)
}