Skip to content

URL Generation ​

Use a shared Go helper to build links to your app's routes. Keep relative links for HTTP responses and use the configured APP_URL when an email or background job needs an absolute URL.

Start with the users route, which serves GET /api/v1/users/:id. Add internal/links/users.go in your project. This complete file uses only the Go standard library.

go
package links

import (
	"fmt"
	"net/url"
)

// UserPath keeps the users route prefix in one place for response links.
func UserPath(id string) string {
	return "/api/v1/users/" + url.PathEscape(id)
}

// Public builds links using the deployment's configured public origin.
type Public struct {
	origin string
}

// NewPublic rejects configuration that would change the destination route.
func NewPublic(raw string) (*Public, error) {
	u, err := url.Parse(raw)
	if err != nil {
		return nil, fmt.Errorf("parse APP_URL: %w", err)
	}
	if (u.Scheme != "http" && u.Scheme != "https") || u.Hostname() == "" ||
		u.User != nil || (u.Path != "" && u.Path != "/") ||
		u.RawQuery != "" || u.ForceQuery || u.Fragment != "" {
		return nil, fmt.Errorf("APP_URL must be an HTTP or HTTPS origin without credentials, a path, a query, or a fragment")
	}
	return &Public{origin: u.Scheme + "://" + u.Host}, nil
}

// UserURL provides an absolute link for clients outside the current site.
func (p *Public) UserURL(id string) string {
	return p.origin + UserPath(id)
}

UserPath("42") returns /api/v1/users/42. Pass a validated user ID and escape each dynamic path segment with url.PathEscape. Keep the route's / separators intact.

This helper assumes the app is served at the origin root. If your deployment mounts the app under a path prefix, extend the helper and its tests to include that prefix.

Add Query Parameters ​

Use url.Values.Encode for query values. It escapes values and sorts keys. The following fragment uses the links package above and the standard library's fmt and net/url packages.

go
query := url.Values{"source": {"email & app"}}
relative := links.UserPath("42") + "?" + query.Encode()
fmt.Println(relative)
// /api/v1/users/42?source=email+%26+app

Generate an Absolute URL ​

Set APP_URL to the public origin in your app configuration. The generated Web API configuration defaults to http://localhost:3000. For a public deployment, use its HTTPS origin.

dotenv
APP_URL=https://app.example.test

Construct links.Public once in the provider that creates your email or notification service. Return configuration errors from that provider and pass the resulting dependency to the service's constructor. This provider fragment assumes imports for os and your module's internal/links package.

go
publicLinks, err := links.NewPublic(os.Getenv("APP_URL"))
if err != nil {
	return nil, err
}

With that configuration, publicLinks.UserURL("42") returns https://app.example.test/api/v1/users/42. Use a configured origin for links sent outside the app. HTTP Runtime covers the separate listener address and port settings.

When your create-user handler saves a user that the GET route can look up, set Location before writing the JSON response. In internal/users/store.go, import your module's internal/links package.

go
ctx.SetHeader("Location", links.UserPath(user.ID))
return ctx.JSON(http.StatusCreated, user)

The response has status 201 and a Location such as /api/v1/users/42. For a browser redirect after a POST, pass the application-built path to ctx.Redirect(http.StatusSeeOther, links.UserPath(user.ID)).

Build redirect targets from known routes and validated IDs. For a user-selected destination, validate it against an allowlist before redirecting.

Verify the URLs ​

Add internal/links/users_test.go beside the helper to check the URL encoding.

go
package links

import "fmt"

// ExampleUserPath checks how the helper escapes a path segment.
func ExampleUserPath() {
	fmt.Println(UserPath("user 123"))
	// Output:
	// /api/v1/users/user%20123
}

Run the tests from the project root.

bash
go test ./internal/links

The test passes when the helper returns the encoded path. Add a handler test for a Location header by following it and checking the resource returned.