| 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 |
|
| 5 |
package elastic |
| 6 |
|
| 7 |
import "net/url" |
| 8 |
|
| 9 |
// canonicalize takes a list of URLs and returns its canonicalized form, i.e. |
| 10 |
// remove anything but scheme, userinfo, host, path, and port. |
| 11 |
// It also removes all trailing slashes. Invalid URLs or URLs that do not |
| 12 |
// use protocol http or https are skipped. |
| 13 |
// |
| 14 |
// Example: |
| 15 |
// http://127.0.0.1:9200/?query=1 -> http://127.0.0.1:9200 |
| 16 |
// http://127.0.0.1:9200/db1/ -> http://127.0.0.1:9200/db1 |
| 17 |
func canonicalize(rawurls ...string) []string { |
| 18 |
var canonicalized []string |
| 19 |
for _, rawurl := range rawurls { |
| 20 |
u, err := url.Parse(rawurl) |
| 21 |
if err == nil { |
| 22 |
if u.Scheme == "http" || u.Scheme == "https" { |
| 23 |
// Trim trailing slashes |
| 24 |
for len(u.Path) > 0 && u.Path[len(u.Path)-1] == '/' { |
| 25 |
u.Path = u.Path[0 : len(u.Path)-1] |
| 26 |
} |
| 27 |
u.Fragment = "" |
| 28 |
u.RawQuery = "" |
| 29 |
canonicalized = append(canonicalized, u.String()) |
| 30 |
} |
| 31 |
} |
| 32 |
} |
| 33 |
return canonicalized |
| 34 |
} |