Files
crowsnest/cmd/frontend/UpSearch.go

38 lines
1.1 KiB
Go
Raw Normal View History

2025-01-02 16:21:02 +01:00
package main
import (
"crowsnest/internal/model"
"html/template"
"net/http"
)
// Enpoint that returns a list of articles given search terms in the post
// request of a search form. Uses the content template.
2025-01-02 16:21:02 +01:00
func (app *App) UpSearch(w http.ResponseWriter, req *http.Request) {
// construct search query
2025-01-03 01:00:06 +01:00
searchTerms := req.FormValue("search")
if searchTerms == "" {
2025-01-02 16:21:02 +01:00
app.Index(w, req)
return
}
2025-01-03 01:00:06 +01:00
// get articles
articles, err := app.articles.Search(searchTerms)
if err != nil {
// treat as no result
//http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// convert to viewmodel
2025-01-02 16:21:02 +01:00
articleVMs := make([]*model.ArticleViewModel, 0, len(articles))
for _, a := range articles {
2025-01-02 16:21:02 +01:00
articleVMs = append(articleVMs, a.ViewModel())
}
// render template
2025-01-02 15:48:55 +01:00
t := template.Must(template.ParseFiles("assets/templates/article.html"))
err = t.ExecuteTemplate(w, "content", articleVMs)
if err != nil { http.Error(w, "Failed to render template", http.StatusInternalServerError); return; }
}