GoBlog/search.go

49 lines
1.1 KiB
Go
Raw 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"
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) {
a.serveIndex(w, r.WithContext(context.WithValue(r.Context(), indexConfigKey, &indexConfig{
path: r.Context().Value(pathKey).(string) + "/" + searchPlaceholder,
})))
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)
}