GoBlog/search.go

58 lines
1.4 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"
"net/url"
2021-02-15 20:35:05 +00:00
"path"
2020-11-15 10:34:48 +00:00
"strings"
)
const defaultSearchPath = "/search"
2020-11-15 10:34:48 +00:00
const searchPlaceholder = "{search}"
func (a *goBlog) serveSearch(w http.ResponseWriter, r *http.Request) {
blog := r.Context().Value(blogKey).(string)
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, templateSearch, &renderData{
BlogString: blog,
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 {
return url.PathEscape(strings.ReplaceAll(base64.StdEncoding.EncodeToString([]byte(search)), "/", "_"))
}
func searchDecode(encoded string) string {
encoded, err := url.PathUnescape(encoded)
if err != nil {
return ""
}
encoded = strings.ReplaceAll(encoded, "_", "/")
db, err := base64.StdEncoding.DecodeString(encoded)
if err != nil {
return ""
}
return string(db)
}