Don Newton | 379ae25 | 2019-04-01 12:17:06 -0400 | [diff] [blame^] | 1 | // 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 | |
| 7 | package address |
| 8 | |
| 9 | import ( |
| 10 | "net" |
| 11 | "strings" |
| 12 | ) |
| 13 | |
| 14 | const defaultPort = "27017" |
| 15 | |
| 16 | // Address is a network address. It can either be an IP address or a DNS name. |
| 17 | type Address string |
| 18 | |
| 19 | // Network is the network protocol for this address. In most cases this will be |
| 20 | // "tcp" or "unix". |
| 21 | func (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. |
| 30 | func (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. |
| 47 | func (a Address) Canonicalize() Address { |
| 48 | return Address(a.String()) |
| 49 | } |