forked from hyperledger/fabric-x-committer
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathendpoint.go
More file actions
72 lines (60 loc) · 1.78 KB
/
Copy pathendpoint.go
File metadata and controls
72 lines (60 loc) · 1.78 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
/*
Copyright IBM Corp. All Rights Reserved.
SPDX-License-Identifier: Apache-2.0
*/
package connection
import (
"net"
"strconv"
"github.com/cockroachdb/errors"
)
// Endpoint describes a remote endpoint.
type Endpoint struct {
Host string `mapstructure:"host" json:"host,omitempty" yaml:"host,omitempty"`
Port int `mapstructure:"port" json:"port,omitempty" yaml:"port,omitempty"`
}
// Empty returns true if no port is assigned.
func (e *Endpoint) Empty() bool {
return e.Port == 0
}
// Address returns a string representation of the endpoint's address.
func (e *Endpoint) Address() string {
return net.JoinHostPort(e.Host, strconv.Itoa(e.Port))
}
// String returns a string representation of the endpoint.
func (e *Endpoint) String() string {
return e.Address()
}
// GetHost returns the host of the endpoint.
func (e *Endpoint) GetHost() string { return e.Host }
// CreateEndpointHP parses an endpoint from give host and port.
// It panics if it fails to parse.
func CreateEndpointHP(host, port string) *Endpoint {
convertedPort, err := strconv.Atoi(port)
if err != nil {
panic(errors.New("could not convert port to integer"))
}
return &Endpoint{
Host: host,
Port: convertedPort,
}
}
// NewEndpoint parses an endpoint from an address string.
func NewEndpoint(hostPort string) (*Endpoint, error) {
if len(hostPort) == 0 {
return &Endpoint{}, nil
}
host, port, err := net.SplitHostPort(hostPort)
if err != nil {
return nil, errors.Wrap(err, "could not split host and port")
}
portInt, err := strconv.Atoi(port)
if err != nil {
return nil, errors.Wrap(err, "could not convert port to integer")
}
return &Endpoint{Host: host, Port: portInt}, nil
}
// NewLocalHost returns a default endpoint "localhost:0".
func NewLocalHost() *Endpoint {
return &Endpoint{Host: "localhost"}
}