Skip to content
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
21 changes: 21 additions & 0 deletions listen_port_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,21 @@
package solution

import "testing"

// TestListenPortReadsEitherAddressForm pins the two shapes Codefly hands a
// service for its own endpoint: a rendered cell writes the bare host:port, a
// local run a URL. The bare form is the one url.Parse misreads as a scheme.
func TestListenPortReadsEitherAddressForm(t *testing.T) {
for address, want := range map[string]string{
"localhost:8080": "8080",
"http://localhost:8080": "8080",
"http://127.0.0.1:41234": "41234",
"[::1]:9000": "9000",
"localhost": "",
"": "",
} {
if got := listenPort(address); got != want {
t.Errorf("listenPort(%q) = %q, want %q", address, got, want)
}
}
}
22 changes: 19 additions & 3 deletions solution.go
Original file line number Diff line number Diff line change
Expand Up @@ -256,6 +256,24 @@ func env(key, fallback string) string {
// could not resolve it. Using the SDK keeps addresses and ports out of the
// runtime: they come from Codefly's runtime-injected endpoint map (or, in a
// local run, its deterministic native workspace map) — never a hardcoded port.
// listenPort is the port of this service's own endpoint address. Codefly hands a
// service its own endpoint as a bare "host:port" (a rendered cell writes
// "localhost:8080"), and other endpoints as URLs; url.Parse reads the bare form
// as scheme "localhost" with no port, which left every rendered solution
// refusing to boot with an empty listen port. Both forms resolve here.
func listenPort(self string) string {
if strings.Contains(self, "://") {
if u, err := url.Parse(self); err == nil {
return u.Port()
}
return ""
}
if _, port, err := net.SplitHostPort(self); err == nil {
return port
}
return ""
}

func address(ctx context.Context, module, service, endpoint, api string) string {
q := codefly.For(ctx).Endpoint(endpoint)
if module != "" {
Expand Down Expand Up @@ -386,9 +404,7 @@ func loadConfig(ctx context.Context, id string) config {
port := env("PORT", "")
if port == "" {
if self := address(ctx, "", "", "http", "http"); self != "" {
if u, err := url.Parse(self); err == nil {
port = u.Port()
}
port = listenPort(self)
}
}
public := env("PUBLIC_URL", "")
Expand Down
Loading