| 1 | // Package peerurl matches configured private peers across HTTP and WebSocket transports. |
| 2 | package peerurl |
| 3 | |
| 4 | import ( |
| 5 | "net/url" |
| 6 | "strings" |
| 7 | ) |
| 8 | |
| 9 | // Match returns the normalized configured base for a source URL. |
| 10 | // WebSocket schemes are mapped to their HTTP equivalents because private Git |
| 11 | // transport probes and signs HTTP repository roots. |
| 12 | func Match(source string, peers []string) string { |
| 13 | u, err := url.Parse(source) |
| 14 | if err != nil { |
| 15 | return "" |
| 16 | } |
| 17 | for _, configured := range peers { |
| 18 | peer, err := url.Parse(strings.TrimRight(strings.TrimSpace(configured), "/" )) |
| 19 | if err != nil || normalizePeerScheme(peer.Scheme) != normalizePeerScheme(u.Scheme) || peer.Host != u.Host { |
| 20 | continue |
| 21 | } |
| 22 | base := strings.TrimRight(peer.Path, "/" ) |
| 23 | if base != "" && u.Path != base && !strings.HasPrefix(u.Path, base+"/" ) { |
| 24 | continue |
| 25 | } |
| 26 | peer.Scheme = normalizePeerScheme(peer.Scheme) |
| 27 | peer.Path = base |
| 28 | peer.RawPath = "" |
| 29 | return strings.TrimRight(peer.String(), "/" ) |
| 30 | } |
| 31 | return "" |
| 32 | } |
| 33 | |
| 34 | func normalizePeerScheme(scheme string) string { |
| 35 | switch scheme { |
| 36 | case "ws" : |
| 37 | return "http" |
| 38 | case "wss" : |
| 39 | return "https" |
| 40 | default: |
| 41 | return scheme |
| 42 | } |
| 43 | } |