|
| 1 | +package config |
| 2 | + |
| 3 | +import ( |
| 4 | + "fmt" |
| 5 | + "net" |
| 6 | + "net/url" |
| 7 | + "strings" |
| 8 | +) |
| 9 | + |
| 10 | +func normalizeServerURL(raw string, tlsEnabled bool, defaultPort int) (string, error) { |
| 11 | + raw = strings.TrimSpace(raw) |
| 12 | + if raw == "" { |
| 13 | + return "", fmt.Errorf("site.server is empty") |
| 14 | + } |
| 15 | + |
| 16 | + scheme := "http" |
| 17 | + if tlsEnabled { |
| 18 | + scheme = "https" |
| 19 | + } |
| 20 | + |
| 21 | + var u *url.URL |
| 22 | + var err error |
| 23 | + if strings.Contains(raw, "://") { |
| 24 | + u, err = url.Parse(raw) |
| 25 | + } else { |
| 26 | + u, err = url.Parse("//" + raw) |
| 27 | + } |
| 28 | + if err != nil { |
| 29 | + return "", fmt.Errorf("invalid server %q: %w", raw, err) |
| 30 | + } |
| 31 | + |
| 32 | + host := u.Host |
| 33 | + if host == "" && u.Path != "" && !strings.Contains(u.Path, "/") { |
| 34 | + host = u.Path |
| 35 | + } |
| 36 | + if host == "" { |
| 37 | + return "", fmt.Errorf("invalid server %q: missing host", raw) |
| 38 | + } |
| 39 | + |
| 40 | + hostName, port := splitHostPort(host) |
| 41 | + if hostName == "" { |
| 42 | + return "", fmt.Errorf("invalid server %q: missing host", raw) |
| 43 | + } |
| 44 | + if port == "" { |
| 45 | + if defaultPort > 0 { |
| 46 | + port = fmt.Sprintf("%d", defaultPort) |
| 47 | + } else if scheme == "https" { |
| 48 | + port = "443" |
| 49 | + } else { |
| 50 | + port = "80" |
| 51 | + } |
| 52 | + } |
| 53 | + |
| 54 | + return fmt.Sprintf("%s://%s", scheme, net.JoinHostPort(hostName, port)), nil |
| 55 | +} |
| 56 | + |
| 57 | +func splitHostPort(host string) (string, string) { |
| 58 | + host = strings.TrimSpace(host) |
| 59 | + if host == "" { |
| 60 | + return "", "" |
| 61 | + } |
| 62 | + if h, p, err := net.SplitHostPort(host); err == nil { |
| 63 | + return trimIPv6Brackets(h), p |
| 64 | + } |
| 65 | + return trimIPv6Brackets(host), "" |
| 66 | +} |
| 67 | + |
| 68 | +func trimIPv6Brackets(h string) string { |
| 69 | + if strings.HasPrefix(h, "[") && strings.HasSuffix(h, "]") { |
| 70 | + return strings.TrimSuffix(strings.TrimPrefix(h, "["), "]") |
| 71 | + } |
| 72 | + return h |
| 73 | +} |
0 commit comments