From 87eb5ed5c0a798ae36a8c1096d2222d878be8762 Mon Sep 17 00:00:00 2001 From: longxboy Date: Mon, 28 Jun 2021 10:20:48 +0800 Subject: [PATCH] add http ip port support (#1115) * add http ip port support * fix example --- internal/host/host.go | 16 ++++++++++++++++ internal/host/host_test.go | 19 +++++++++++++++++++ transport/http/client.go | 3 ++- 3 files changed, 37 insertions(+), 1 deletion(-) diff --git a/internal/host/host.go b/internal/host/host.go index 193056d6f..dd7c23e73 100644 --- a/internal/host/host.go +++ b/internal/host/host.go @@ -6,6 +6,22 @@ import ( "strconv" ) +// ExtractHostPort from address +func ExtractHostPort(addr string) (host string, port uint64, err error) { + var ( + ports string + ) + host, ports, err = net.SplitHostPort(addr) + if err != nil { + return + } + port, err = strconv.ParseUint(ports, 10, 16) + if err != nil { + return + } + return +} + func isValidIP(addr string) bool { ip := net.ParseIP(addr) return ip.IsGlobalUnicast() && !ip.IsInterfaceLocalMulticast() diff --git a/internal/host/host_test.go b/internal/host/host_test.go index 36d6548b3..930e8c3e4 100644 --- a/internal/host/host_test.go +++ b/internal/host/host_test.go @@ -86,3 +86,22 @@ func TestPort(t *testing.T) { t.Fatalf("expected: %s got %d", lis.Addr().String(), port) } } + +func TestExtractHostPort(t *testing.T) { + host, port, err := ExtractHostPort("127.0.0.1:8000") + if err != nil { + t.Fatalf("expected: %v got %v", nil, err) + } + t.Logf("host port: %s, %d", host, port) + + host, port, err = ExtractHostPort("www.bilibili.com:80") + if err != nil { + t.Fatalf("expected: %v got %v", nil, err) + } + t.Logf("host port: %s, %d", host, port) + + host, port, err = ExtractHostPort("consul://2/33") + if err == nil { + t.Fatalf("expected: not nil got %v", nil) + } +} diff --git a/transport/http/client.go b/transport/http/client.go index 8eb424760..e41ae3d3b 100644 --- a/transport/http/client.go +++ b/transport/http/client.go @@ -11,6 +11,7 @@ import ( "github.com/go-kratos/kratos/v2/encoding" "github.com/go-kratos/kratos/v2/errors" + "github.com/go-kratos/kratos/v2/internal/host" "github.com/go-kratos/kratos/v2/internal/httputil" "github.com/go-kratos/kratos/v2/middleware" "github.com/go-kratos/kratos/v2/registry" @@ -150,7 +151,7 @@ func NewClient(ctx context.Context, opts ...ClientOption) (*Client, error) { if r, err = newResolver(ctx, options.discovery, target, options.balancer); err != nil { return nil, fmt.Errorf("[http client] new resolver failed!err: %v", options.endpoint) } - } else { + } else if _, _, err := host.ExtractHostPort(options.endpoint); err != nil { return nil, fmt.Errorf("[http client] invalid endpoint format: %v", options.endpoint) } }