blob: c2a3bb7ba4f4618a4fe5d8da88c1fbb184ad0665 [file] [log] [blame]
Don Newton379ae252019-04-01 12:17:06 -04001// Copyright (C) MongoDB, Inc. 2017-present.
2//
3// Licensed under the Apache License, Version 2.0 (the "License"); you may
4// not use this file except in compliance with the License. You may obtain
5// a copy of the License at http://www.apache.org/licenses/LICENSE-2.0
6
7package address
8
9import (
10 "net"
11 "strings"
12)
13
14const defaultPort = "27017"
15
16// Address is a network address. It can either be an IP address or a DNS name.
17type Address string
18
19// Network is the network protocol for this address. In most cases this will be
20// "tcp" or "unix".
21func (a Address) Network() string {
22 if strings.HasSuffix(string(a), "sock") {
23 return "unix"
24 }
25 return "tcp"
26}
27
28// String is the canonical version of this address, e.g. localhost:27017,
29// 1.2.3.4:27017, example.com:27017.
30func (a Address) String() string {
31 // TODO: unicode case folding?
32 s := strings.ToLower(string(a))
33 if len(s) == 0 {
34 return ""
35 }
36 if a.Network() != "unix" {
37 _, _, err := net.SplitHostPort(s)
38 if err != nil && strings.Contains(err.Error(), "missing port in address") {
39 s += ":" + defaultPort
40 }
41 }
42
43 return s
44}
45
46// Canonicalize creates a canonicalized address.
47func (a Address) Canonicalize() Address {
48 return Address(a.String())
49}