chore: add location header

This commit is contained in:
johnnyjoy 2024-08-18 10:20:50 +08:00
parent 80548aaf2c
commit a3943f5b2d
3 changed files with 42 additions and 1 deletions

View File

@ -4,6 +4,7 @@ import (
"crypto/rand" "crypto/rand"
"math/big" "math/big"
"net/mail" "net/mail"
"net/url"
"strconv" "strconv"
"strings" "strings"
) )
@ -55,3 +56,9 @@ func RandomString(n int) (string, error) {
} }
return sb.String(), nil 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 != ""
}

View File

@ -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)
}
}
}

View File

@ -92,9 +92,13 @@ func (s *FrontendService) registerRoutes(e *echo.Echo) {
} }
metric.Enqueue("shortcut view") 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`. // Inject shortcut metadata into `index.html`.
indexHTML := strings.ReplaceAll(rawIndexHTML, headerMetadataPlaceholder, generateShortcutMetadata(shortcut).String()) 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 { e.GET("/c/:collectionName", func(c echo.Context) error {