Skip to content
This commit does not belong to any branch on this repository, and may belong to a fork outside of the repository.

Commit ab0ecfb

Browse files
committedJul 25, 2024
Account for port in Host header
When using host-based routing, ensure we always route on the host name part only. If there's a port in the Host header value, we should ignore it.
1 parent 0718fac commit ab0ecfb

File tree

2 files changed

+19
-1
lines changed

2 files changed

+19
-1
lines changed
 

‎internal/server/router.go

+7-1
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import (
55
"encoding/json"
66
"errors"
77
"log/slog"
8+
"net"
89
"net/http"
910
"os"
1011
"sync"
@@ -228,7 +229,12 @@ func (r *Router) saveStateSnapshot() error {
228229
}
229230

230231
func (r *Router) serviceForRequest(req *http.Request) *Service {
231-
return r.serviceForHost(req.Host)
232+
host, _, err := net.SplitHostPort(req.Host)
233+
if err != nil {
234+
host = req.Host
235+
}
236+
237+
return r.serviceForHost(host)
232238
}
233239

234240
func (r *Router) serviceForHost(host string) *Service {

‎internal/server/router_test.go

+12
Original file line numberDiff line numberDiff line change
@@ -32,6 +32,18 @@ func TestRouter_ActiveServiceForHost(t *testing.T) {
3232
assert.Equal(t, "first", body)
3333
}
3434

35+
func TestRouter_ActiveServiceForHostContainingPort(t *testing.T) {
36+
router := testRouter(t)
37+
_, target := testBackend(t, "first", http.StatusOK)
38+
39+
require.NoError(t, router.SetServiceTarget("service1", "dummy.example.com", target, defaultServiceOptions, defaultTargetOptions, DefaultDeployTimeout, DefaultDrainTimeout))
40+
41+
statusCode, body := sendGETRequest(router, "http://dummy.example.com:80/")
42+
43+
assert.Equal(t, http.StatusOK, statusCode)
44+
assert.Equal(t, "first", body)
45+
}
46+
3547
func TestRouter_ActiveServiceWithoutHost(t *testing.T) {
3648
router := testRouter(t)
3749
_, target := testBackend(t, "first", http.StatusOK)

0 commit comments

Comments
 (0)