Skip to content

v0.0.16 - URL Encoding for Path Parameters

Choose a tag to compare

@jackielii jackielii released this 27 Oct 22:26
· 161 commits to main since this release

v0.0.16 - URL Encoding for Path Parameters

πŸ”’ Security & Safety Improvements

URL Encoding for Path Parameters

Added proper URL encoding to URLFor() function to prevent malformed URLs from special characters in path parameters.

Key Features:

  • βœ… Regular parameters ({id}): All special characters encoded, including slashes
  • βœ… Wildcard parameters ({path...}): Slashes preserved, other special chars encoded
  • βœ… RFC 3986 compliant: & and = allowed in path segments (not encoded)
  • βœ… Security: Prevents URL injection via special characters (/, ?, &, #)

πŸ“ Examples

Regular Parameters

// Spaces
URLFor(ctx, userPage, "hello world")
// β†’ /users/hello%20world

// Slashes (prevented from creating unintended path segments)
URLFor(ctx, userPage, "hello/world")
// β†’ /users/hello%2Fworld

// Special characters
URLFor(ctx, userPage, "user#123")
// β†’ /users/user%23123

Wildcard Parameters

// Slashes preserved in wildcards
URLFor(ctx, filePage, "docs/api/v1/reference.md")
// β†’ /files/docs/api/v1/reference.md

// Special chars still encoded
URLFor(ctx, filePage, "my documents/file name.pdf")
// β†’ /files/my%20documents/file%20name.pdf

Query String Composition

// Using []any{page, "?param={param}"} pattern
URLFor(ctx, []any{searchPage, "?q={query}"}, "hello world")
// β†’ /search?q=hello%20world

// Complex compositions
URLFor(ctx, []any{apiPage, "/users/{id}", "?format={format}"},
    "123", "json")
// β†’ /api/users/123?format=json

πŸ§ͺ Testing

Added comprehensive test coverage:

  • TestURLFor_withSpecialCharacters: Validates encoding behavior for various special characters
  • TestURLFor_withQueryStringComposition: Tests query string and fragment composition patterns

All existing tests pass, ensuring 100% backward compatibility.

πŸ”§ Technical Details

Implementation:

  • New encodePathSegment() helper function centralizes encoding logic
  • Added wildcard field to segment struct for proper parameter tracking
  • Uses url.PathEscape() for RFC 3986 compliant encoding
  • Wildcard encoding: splits on /, escapes each segment, then rejoins

Security Benefits:

  • Prevents URL structure manipulation via injected slashes
  • Protects against query string injection via ? and &
  • Handles hash fragments correctly to prevent anchor injection
  • Maintains URL integrity with proper character escaping

Full Changelog: v0.0.15...v0.0.16