GoBlog/search.go

47 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"
2021-02-15 20:35:05 +00:00
"path"
2020-11-15 10:34:48 +00:00
"strings"
)
const searchPlaceholder = "{search}"
2021-02-15 20:35:05 +00:00
func serveSearch(blog string, servePath string) func(w http.ResponseWriter, r *http.Request) {
2020-11-15 10:34:48 +00:00
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 != "" {
2021-02-15 20:35:05 +00:00
http.Redirect(w, r, path.Join(servePath, searchEncode(q)), http.StatusFound)
2020-11-15 10:34:48 +00:00
return
}
2021-02-20 22:35:16 +00:00
render(w, r, templateSearch, &renderData{
2021-01-17 11:53:07 +00:00
BlogString: blog,
2021-02-15 20:35:05 +00:00
Canonical: appConfig.Server.PublicAddress + servePath,
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)
}