GoBlog/search.go

46 lines
1.0 KiB
Go
Raw Normal View History

2020-11-15 10:34:48 +00:00
package main
import (
"encoding/base64"
"net/http"
"net/url"
"strings"
)
const searchPlaceholder = "{search}"
func serveSearch(blog string, path string) func(w http.ResponseWriter, r *http.Request) {
return func(w http.ResponseWriter, r *http.Request) {
err := r.ParseForm()
if err != nil {
2020-12-24 09:09:34 +00:00
serveError(w, r, err.Error(), http.StatusBadRequest)
2020-11-15 10:34:48 +00:00
return
}
if q := r.Form.Get("q"); q != "" {
http.Redirect(w, r, path+"/"+searchEncode(q), http.StatusFound)
return
}
render(w, templateSearch, &renderData{
2021-01-17 11:53:07 +00:00
BlogString: blog,
2020-11-15 10:34:48 +00:00
Canonical: appConfig.Server.PublicAddress + path,
})
}
}
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)
}