add search
This commit is contained in:
@@ -7,13 +7,28 @@ import (
|
||||
"fmt"
|
||||
"html/template"
|
||||
"net/http"
|
||||
"strings"
|
||||
)
|
||||
|
||||
type articleDateOrder struct {}
|
||||
func (ord articleDateOrder) Weight(a *model.Article) int {
|
||||
return int(a.PublishDate.Unix()) * -1
|
||||
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")
|
||||
|
||||
@@ -24,9 +39,29 @@ func index(w http.ResponseWriter, req *http.Request) {
|
||||
_ = 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"))
|
||||
|
||||
Reference in New Issue
Block a user