util.go 983 B

12345678910111213141516171819202122232425262728293031323334
  1. // Copyright (C) 2016 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at http://mozilla.org/MPL/2.0/.
  6. package connections
  7. import (
  8. "net"
  9. "net/url"
  10. "strconv"
  11. "strings"
  12. )
  13. func fixupPort(uri *url.URL, defaultPort int) *url.URL {
  14. copyURI := *uri
  15. host, port, err := net.SplitHostPort(uri.Host)
  16. if err != nil && strings.Contains(err.Error(), "missing port") {
  17. // addr is on the form "1.2.3.4" or "[fe80::1]"
  18. host = uri.Host
  19. if strings.HasPrefix(host, "[") && strings.HasSuffix(host, "]") {
  20. // net.JoinHostPort will add the brackets again
  21. host = host[1 : len(host)-1]
  22. }
  23. copyURI.Host = net.JoinHostPort(host, strconv.Itoa(defaultPort))
  24. } else if err == nil && port == "" {
  25. // addr is on the form "1.2.3.4:" or "[fe80::1]:"
  26. copyURI.Host = net.JoinHostPort(host, strconv.Itoa(defaultPort))
  27. }
  28. return &copyURI
  29. }