add http ip port support (#1115)

* add http ip port support

* fix example
pull/1116/head
longxboy 3 years ago committed by GitHub
parent c8b477d167
commit 87eb5ed5c0
No known key found for this signature in database
GPG Key ID: 4AEE18F83AFDEB23
  1. 16
      internal/host/host.go
  2. 19
      internal/host/host_test.go
  3. 3
      transport/http/client.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()

@ -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)
}
}

@ -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)
}
}

Loading…
Cancel
Save