Files
crowsnest/cmd/frontend/main.go

76 lines
2.0 KiB
Go
Raw Normal View History

2024-12-20 01:15:56 +01:00
package main
import (
//"fmt"
"crowsnest/internal/data"
"crowsnest/internal/model"
"fmt"
"html/template"
"net/http"
2025-01-02 00:35:41 +01:00
"strings"
2024-12-20 01:15:56 +01:00
)
type articleDateOrder struct {}
func (ord articleDateOrder) Weight(a *model.Article) int {
2025-01-02 00:35:41 +01:00
return int(a.PublishDate.Unix())
}
2025-01-02 00:35:41 +01:00
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{})
2024-12-20 01:15:56 +01:00
t := template.Must(template.ParseFiles("templates/article.html", "templates/layout.html"))
_ = t.ExecuteTemplate(w, "base", articles[:10])
2024-12-27 22:34:43 +01:00
}
2025-01-02 00:35:41 +01:00
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)
}
2024-12-20 01:15:56 +01:00
func main() {
// routes
http.HandleFunc("/", index)
2025-01-02 00:35:41 +01:00
http.HandleFunc("/search", search)
2024-12-20 01:15:56 +01:00
// serve files from the "static" directory
2024-12-20 01:15:56 +01:00
fs := http.FileServer(http.Dir("./static"))
http.Handle("/static", http.StripPrefix("/", fs))
2024-12-20 01:15:56 +01:00
t := template.Must(template.ParseFiles("templates/article.html"))
fmt.Println(t)
2024-12-27 03:25:44 +01:00
// start server
http.ListenAndServe(":8080", nil)
2024-12-20 01:15:56 +01:00
}