Skip to content

Commit

Permalink
Fix binding http/https services on custom ports (TykTechnologies#2570)
Browse files Browse the repository at this point in the history
  • Loading branch information
gernest authored and buger committed Sep 27, 2019
1 parent 92e39c5 commit 7d238eb
Show file tree
Hide file tree
Showing 2 changed files with 56 additions and 0 deletions.
1 change: 1 addition & 0 deletions gateway/api_loader.go
Original file line number Diff line number Diff line change
Expand Up @@ -573,6 +573,7 @@ func loadHTTPService(spec *APISpec, apisByListen map[string]int, gs *generalStor
router := muxer.router(port, spec.Protocol)
if router == nil {
router = mux.NewRouter()
muxer.setRouter(port, spec.Protocol, router)
}

hostname := config.Global().HostName
Expand Down
55 changes: 55 additions & 0 deletions gateway/proxy_muxer_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,8 @@ package gateway

import (
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
Expand Down Expand Up @@ -151,6 +153,24 @@ func TestTCP_missing_port(t *testing.T) {
}
}

// getUnusedPort returns a tcp port that is a vailable for binding.
func getUnusedPort() (int, error) {
rp, err := net.Listen("tcp", "127.0.0.1:0")
if err != nil {
return 0, err
}
defer rp.Close()
_, port, err := net.SplitHostPort(rp.Addr().String())
if err != nil {
return 0, err
}
p, err := strconv.Atoi(port)
if err != nil {
return 0, err
}
return p, nil
}

func TestCheckPortWhiteList(t *testing.T) {
base := config.Global()
cases := []struct {
Expand Down Expand Up @@ -234,3 +254,38 @@ func TestCheckPortWhiteList(t *testing.T) {
})
}
}

func TestHTTP_custom_ports(t *testing.T) {
ts := StartTest()
defer ts.Close()
echo := "Hello, world"
us := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(echo))
}))
defer us.Close()
port, err := getUnusedPort()
if err != nil {
t.Fatal(err)
}
EnablePort(port, "http")
BuildAndLoadAPI(func(spec *APISpec) {
spec.Proxy.ListenPath = "/"
spec.Protocol = "http"
spec.ListenPort = port
spec.Proxy.TargetURL = us.URL
})
s := fmt.Sprintf("http://localhost:%d", port)
w, err := http.Get(s)
if err != nil {
t.Fatal(err)
}
defer w.Body.Close()
b, err := ioutil.ReadAll(w.Body)
if err != nil {
t.Fatal(err)
}
bs := string(b)
if bs != echo {
t.Errorf("expected %s to %s", echo, bs)
}
}

0 comments on commit 7d238eb

Please sign in to comment.