Skip to content
This repository was archived by the owner on Oct 5, 2023. It is now read-only.

fix: use https URI when multiaddress specifies tls #177

Merged
merged 1 commit into from
May 15, 2023
Merged
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
16 changes: 15 additions & 1 deletion api.go
Original file line number Diff line number Diff line change
Expand Up @@ -107,7 +107,21 @@ func NewApiWithClient(a ma.Multiaddr, c *http.Client) (*HttpApi, error) {
}
}

return NewURLApiWithClient(url, c)
proto := "http://"

// By default, DialArgs is going to provide details suitable for connecting
// a socket to, but not really suitable for making an informed choice of http
// protocol. For multiaddresses specifying tls and/or https we want to make
// a https request instead of a http request.
protocols := a.Protocols()
for _, p := range protocols {
if p.Code == ma.P_HTTPS || p.Code == ma.P_TLS {
proto = "https://"
break
}
}

return NewURLApiWithClient(proto+url, c)
}

func NewURLApiWithClient(url string, c *http.Client) (*HttpApi, error) {
Expand Down
28 changes: 28 additions & 0 deletions api_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -246,3 +246,31 @@ func Test_NewURLApiWithClient_With_Headers(t *testing.T) {
t.Fatal(err)
}
}

func Test_NewURLApiWithClient_HTTP_Variant(t *testing.T) {
testcases := []struct {
address string
expected string
}{
{address: "/ip4/127.0.0.1/tcp/80", expected: "http://127.0.0.1:80"},
{address: "/ip4/127.0.0.1/tcp/443/tls", expected: "https://127.0.0.1:443"},
{address: "/ip4/127.0.0.1/tcp/443/https", expected: "https://127.0.0.1:443"},
{address: "/ip4/127.0.0.1/tcp/443/tls/http", expected: "https://127.0.0.1:443"},
}

for _, tc := range testcases {
address, err := ma.NewMultiaddr(tc.address)
if err != nil {
t.Fatal(err)
}

api, err := NewApiWithClient(address, &http.Client{})
if err != nil {
t.Fatal(err)
}

if api.url != tc.expected {
t.Errorf("Expected = %s; got %s", tc.expected, api.url)
}
}
}