File: hostmaybeport.go

package info (click to toggle)
golang-github-anacrolix-missinggo 2.1.0-4
  • links: PTS, VCS
  • area: main
  • in suites: bullseye, sid
  • size: 836 kB
  • sloc: makefile: 4
file content (52 lines) | stat: -rw-r--r-- 1,155 bytes parent folder | download
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
package missinggo

import (
	"net"
	"strconv"
	"strings"
)

// Represents a split host port.
type HostMaybePort struct {
	Host   string // Just the host, with no port.
	Port   int    // The port if NoPort is false.
	NoPort bool   // Whether a port is specified.
	Err    error  // The error returned from net.SplitHostPort.
}

func (me *HostMaybePort) String() string {
	if me.NoPort {
		return me.Host
	}
	return net.JoinHostPort(me.Host, strconv.FormatInt(int64(me.Port), 10))
}

// Parse a "hostport" string, a concept that floats around the stdlib a lot
// and is painful to work with. If no port is present, what's usually present
// is just the host.
func SplitHostMaybePort(hostport string) HostMaybePort {
	host, portStr, err := net.SplitHostPort(hostport)
	if err != nil {
		if strings.Contains(err.Error(), "missing port") {
			return HostMaybePort{
				Host:   hostport,
				NoPort: true,
			}
		}
		return HostMaybePort{
			Err: err,
		}
	}
	portI64, err := strconv.ParseInt(portStr, 0, 0)
	if err != nil {
		return HostMaybePort{
			Host: host,
			Port: -1,
			Err:  err,
		}
	}
	return HostMaybePort{
		Host: host,
		Port: int(portI64),
	}
}