open urls directly when searching for them

This commit is contained in:
Timon Ringwald 2022-05-08 18:17:50 +02:00
parent d3fc636cd9
commit e9e6f9b2a8

18
main.go
View File

@ -7,6 +7,8 @@ import (
"html/template"
"io"
"net/http"
"net/url"
"strings"
_ "embed"
)
@ -91,6 +93,22 @@ func icons(w http.ResponseWriter, r *http.Request) {
func search(w http.ResponseWriter, r *http.Request) {
r.ParseForm()
query := r.Form.Get("query")
if uri, err := ParseURI(query); err == nil {
// url
w.Header().Add("Location", uri.String())
w.WriteHeader(http.StatusMovedPermanently)
} else {
// search string
w.Header().Add("Location", fmt.Sprintf("https://duckduckgo.com/?q=%s", query))
w.WriteHeader(http.StatusMovedPermanently)
}
}
func ParseURI(uri string) (*url.URL, error) {
if !strings.HasPrefix(uri, "http://") && !strings.HasPrefix(uri, "https://") {
uri = "https://" + uri
}
ret, err := url.ParseRequestURI(uri)
return ret, err
}