host.go 530 B

123456789101112131415161718192021222324252627
  1. package utils
  2. import (
  3. "net/url"
  4. "strings"
  5. )
  6. // HostnameFromAddr determines the hostname in an address string
  7. func HostnameFromAddr(addr string) (string, error) {
  8. p, err := url.Parse(addr)
  9. if err != nil {
  10. return "", err
  11. }
  12. h := p.Host
  13. // copied from https://golang.org/src/net/http/transport.go
  14. if hasPort(h) {
  15. h = h[:strings.LastIndex(h, ":")]
  16. }
  17. return h, nil
  18. }
  19. // copied from https://golang.org/src/net/http/http.go
  20. func hasPort(s string) bool {
  21. return strings.LastIndex(s, ":") > strings.LastIndex(s, "]")
  22. }