From a3943f5b2d57e4acec1763877f2bdd58d26405eb Mon Sep 17 00:00:00 2001 From: johnnyjoy Date: Sun, 18 Aug 2024 10:20:50 +0800 Subject: [PATCH] chore: add location header --- internal/util/util.go | 7 +++++++ internal/util/util_test.go | 30 ++++++++++++++++++++++++++++++ server/route/frontend/frontend.go | 6 +++++- 3 files changed, 42 insertions(+), 1 deletion(-) diff --git a/internal/util/util.go b/internal/util/util.go index 2ee66203..659fc093 100644 --- a/internal/util/util.go +++ b/internal/util/util.go @@ -4,6 +4,7 @@ import ( "crypto/rand" "math/big" "net/mail" + "net/url" "strconv" "strings" ) @@ -55,3 +56,9 @@ func RandomString(n int) (string, error) { } return sb.String(), nil } + +// ValidateURI validates the URI. +func ValidateURI(uri string) bool { + u, err := url.Parse(uri) + return err == nil && u.Scheme != "" && u.Host != "" +} diff --git a/internal/util/util_test.go b/internal/util/util_test.go index 75f5e155..6071ed71 100644 --- a/internal/util/util_test.go +++ b/internal/util/util_test.go @@ -29,3 +29,33 @@ func TestValidateEmail(t *testing.T) { } } } + +func TestValidateURI(t *testing.T) { + tests := []struct { + uri string + want bool + }{ + { + uri: "https://localhsot:3000", + want: true, + }, + { + uri: "https://yourselfhosted.com", + want: true, + }, + { + uri: "google.com", + want: false, + }, + { + uri: "i don't know", + want: false, + }, + } + for _, test := range tests { + result := ValidateURI(test.uri) + if result != test.want { + t.Errorf("Validate URI %s: got result %v, want %v.", test.uri, result, test.want) + } + } +} diff --git a/server/route/frontend/frontend.go b/server/route/frontend/frontend.go index f8fb2884..abc2a937 100644 --- a/server/route/frontend/frontend.go +++ b/server/route/frontend/frontend.go @@ -92,9 +92,13 @@ func (s *FrontendService) registerRoutes(e *echo.Echo) { } metric.Enqueue("shortcut view") + // Only set the `Location` header if the link is a valid URI. + if util.ValidateURI(shortcut.Link) { + c.Response().Header().Set("Location", shortcut.Link) + } // Inject shortcut metadata into `index.html`. indexHTML := strings.ReplaceAll(rawIndexHTML, headerMetadataPlaceholder, generateShortcutMetadata(shortcut).String()) - return c.HTML(http.StatusOK, indexHTML) + return c.HTML(http.StatusSeeOther, indexHTML) }) e.GET("/c/:collectionName", func(c echo.Context) error {