Documentation
¶
Overview ¶
Package hostrouter provides host-based HTTP routing.
It routes incoming requests to different handlers based on the Host header, supporting both exact matches and wildcard patterns.
Host Patterns ¶
Two pattern types are supported:
- Exact: "api.example.com" matches only that host
- Wildcard: "*.example.com" matches any subdomain (foo.example.com, bar.example.com)
Exact matches take priority over wildcard matches. Host matching is case-insensitive, and ports are stripped before matching.
Usage ¶
routes := hostrouter.Routes{
"api.example.com": apiHandler,
"*.example.com": wildcardHandler,
}
router := hostrouter.New(routes, defaultHandler)
http.ListenAndServe(":8080", router)
IPv6 Support ¶
IPv6 addresses are supported. The router correctly handles addresses with ports like "[::1]:8080" by preserving the brackets during normalization.
Helper Functions ¶
The package provides helper functions for extracting domain information:
// Get the normalized domain from a request domain := hostrouter.GetDomain(r) // "example.com:8080" -> "example.com" // Extract subdomain given a base domain subdomain := hostrouter.GetSubdomain(r, "example.com") // "foo.example.com" -> "foo"
These helpers are used internally by forge.Context.Domain() and forge.Context.Subdomain().
Index ¶
Constants ¶
This section is empty.
Variables ¶
This section is empty.
Functions ¶
func GetDomain ¶
GetDomain returns the normalized domain from the request Host header. Strips port, handles IPv6, and converts to lowercase.
Examples:
"example.com:8080" -> "example.com" "[::1]:8080" -> "[::1]" "Example.COM" -> "example.com"
func GetSubdomain ¶
GetSubdomain extracts the subdomain from a request given a base domain. Returns empty string if host doesn't match the base domain or has no subdomain.
Examples:
GetSubdomain(req, "example.com") // req.Host = "foo.example.com" -> "foo" GetSubdomain(req, "example.com") // req.Host = "bar.foo.example.com" -> "bar.foo" GetSubdomain(req, "example.com") // req.Host = "example.com" -> "" GetSubdomain(req, "example.com") // req.Host = "other.com" -> ""
Types ¶
type Router ¶
type Router struct {
// contains filtered or unexported fields
}
Router routes requests based on the Host header. It supports exact matches and wildcard patterns.