diff --git a/runtime/environment.go b/runtime/environment.go index 9430d74..d925148 100644 --- a/runtime/environment.go +++ b/runtime/environment.go @@ -58,25 +58,26 @@ func (e Environment) Validate() error { } } -func (e Environment) Canonical(page string) template.URL { - page = strings.TrimPrefix(page, "/") +func (e Environment) Canonical(urlpath string, args ...any) template.URL { + s := fmt.Sprintf(urlpath, args...) + p := strings.TrimPrefix(s, "/") - var canonical string + var c string switch e.environment { case Production: - canonical = "https://" + e.domain + "/" + page + c = "https://" + e.domain + "/" + p case Staging: - canonical = "https://stage." + e.domain + "/" + page + c = "https://stage." + e.domain + "/" + p default: - canonical = "http://localhost:" + strconv.Itoa(LocalPort) + "/" + page + c = "http://localhost:" + strconv.Itoa(LocalPort) + "/" + p } - canonical = strings.TrimSuffix(canonical, "/") + canonical := strings.TrimSuffix(c, "/") u, err := url.Parse(canonical) if err != nil { - panic(fmt.Sprintf("runtime: unable to create url for page %q", page)) + panic(fmt.Sprintf("runtime: unable to create url for page %q", urlpath)) } clean := u.String() diff --git a/runtime/environment_test.go b/runtime/environment_test.go index 10fe3ea..07b8ee5 100644 --- a/runtime/environment_test.go +++ b/runtime/environment_test.go @@ -72,4 +72,10 @@ func TestEnvironment_Canonical(t *testing.T) { result := e.Canonical("") must.Eq(t, result, "https://example.com") }) + + t.Run("format", func(t *testing.T) { + e := Setup(&Config{Environment: "production", Domain: "example.com"}) + result := e.Canonical("/about/%s/%d", "content", 42) + must.Eq(t, result, "https://example.com/about/content/42") + }) }