canonicalize.go 1.1 KB

12345678910111213141516171819202122232425262728293031323334
  1. // Copyright 2012-present Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import "net/url"
  6. // canonicalize takes a list of URLs and returns its canonicalized form, i.e.
  7. // remove anything but scheme, userinfo, host, path, and port.
  8. // It also removes all trailing slashes. Invalid URLs or URLs that do not
  9. // use protocol http or https are skipped.
  10. //
  11. // Example:
  12. // http://127.0.0.1:9200/?query=1 -> http://127.0.0.1:9200
  13. // http://127.0.0.1:9200/db1/ -> http://127.0.0.1:9200/db1
  14. func canonicalize(rawurls ...string) []string {
  15. var canonicalized []string
  16. for _, rawurl := range rawurls {
  17. u, err := url.Parse(rawurl)
  18. if err == nil {
  19. if u.Scheme == "http" || u.Scheme == "https" {
  20. // Trim trailing slashes
  21. for len(u.Path) > 0 && u.Path[len(u.Path)-1] == '/' {
  22. u.Path = u.Path[0 : len(u.Path)-1]
  23. }
  24. u.Fragment = ""
  25. u.RawQuery = ""
  26. canonicalized = append(canonicalized, u.String())
  27. }
  28. }
  29. }
  30. return canonicalized
  31. }