From e9e6f9b2a8e83c54a6b51f4850b09958420406b7 Mon Sep 17 00:00:00 2001 From: Timon Ringwald Date: Sun, 8 May 2022 18:17:50 +0200 Subject: [PATCH] open urls directly when searching for them --- main.go | 22 ++++++++++++++++++++-- 1 file changed, 20 insertions(+), 2 deletions(-) diff --git a/main.go b/main.go index 0b96d7e..2aa5804 100644 --- a/main.go +++ b/main.go @@ -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") - w.Header().Add("Location", fmt.Sprintf("https://duckduckgo.com/?q=%s", query)) - w.WriteHeader(http.StatusMovedPermanently) + + 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 }