Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
15 changes: 13 additions & 2 deletions vhost.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,14 +3,25 @@

package echo

import "net/http"
import (
"net/http"
"strings"
)

// NewVirtualHostHandler creates instance of Echo that routes requests to given virtual hosts
// when hosts in request does not exist in given map the request is served by returned Echo instance.
//
// Host names are matched case-insensitively (RFC 9110 Section 4.2.3), so a request with
// `Host: Example.com` reaches the instance registered as `example.com`. The map is copied,
// later changes to it have no effect.
func NewVirtualHostHandler(vhosts map[string]*Echo) *Echo {
e := New()
hosts := make(map[string]*Echo, len(vhosts))
for host, vhost := range vhosts {
hosts[strings.ToLower(host)] = vhost
}
e.serveHTTPFunc = func(w http.ResponseWriter, r *http.Request) {
if vh, ok := vhosts[r.Host]; ok {
if vh, ok := hosts[strings.ToLower(r.Host)]; ok {
vh.ServeHTTP(w, r)
return
}
Expand Down
7 changes: 7 additions & 0 deletions vhost_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -72,6 +72,13 @@ func TestVirtualHostHandler(t *testing.T) {
expectBody: http.StatusText(http.StatusOK),
expectStatus: http.StatusOK,
},
{
name: "OK Host Root, host in different case",
whenHost: "OK.Com",
whenPath: "/",
expectBody: http.StatusText(http.StatusOK),
expectStatus: http.StatusOK,
},
{
name: "Teapot Host Root",
whenHost: "teapot.com",
Expand Down