GoBlog/search.go

60 lines
1.5 KiB
Go
Raw Permalink Normal View History

2020-11-15 10:34:48 +00:00
package main
import (
"context"
2020-11-15 10:34:48 +00:00
"encoding/base64"
"net/http"
2021-02-15 20:35:05 +00:00
"path"
2023-09-07 13:46:51 +00:00
"github.com/go-chi/chi/v5"
2020-11-15 10:34:48 +00:00
)
const defaultSearchPath = "/search"
2020-11-15 10:34:48 +00:00
const searchPlaceholder = "{search}"
func (a *goBlog) serveSearch(w http.ResponseWriter, r *http.Request) {
servePath := r.Context().Value(pathKey).(string)
err := r.ParseForm()
if err != nil {
a.serveError(w, r, err.Error(), http.StatusBadRequest)
return
}
if q := r.Form.Get("q"); q != "" {
// Clean query
2021-09-01 09:14:49 +00:00
q = cleanHTMLText(q)
// Redirect to results
http.Redirect(w, r, path.Join(servePath, searchEncode(q)), http.StatusFound)
return
2020-11-15 10:34:48 +00:00
}
a.render(w, r, a.renderSearch, &renderData{
Canonical: a.getFullAddress(servePath),
})
}
func (a *goBlog) serveSearchResult(w http.ResponseWriter, r *http.Request) {
2023-09-07 13:46:51 +00:00
var searchParamValue, decodedSearch string
// Get search parameter from path
searchParamValue = chi.URLParam(r, "search")
if searchParamValue != "" {
// Decode and sanitize search
decodedSearch = cleanHTMLText(searchDecode(searchParamValue))
}
// Serve index
a.serveIndex(w, r.WithContext(context.WithValue(r.Context(), indexConfigKey, &indexConfig{
2023-09-07 13:46:51 +00:00
path: r.Context().Value(pathKey).(string) + "/" + searchParamValue,
search: decodedSearch,
})))
2020-11-15 10:34:48 +00:00
}
func searchEncode(search string) string {
2023-01-24 13:59:01 +00:00
return base64.URLEncoding.EncodeToString([]byte(search))
2020-11-15 10:34:48 +00:00
}
func searchDecode(encoded string) string {
2023-01-24 13:59:01 +00:00
db, err := base64.URLEncoding.DecodeString(encoded)
2020-11-15 10:34:48 +00:00
if err != nil {
return ""
}
return string(db)
}