-
Notifications
You must be signed in to change notification settings - Fork 3
/
service_name_extractor.go
80 lines (69 loc) · 2.02 KB
/
service_name_extractor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
//
//
// Tencent is pleased to support the open source community by making tRPC available.
//
// Copyright (C) 2023 THL A29 Limited, a Tencent company.
// All rights reserved.
//
// If you have downloaded a copy of the tRPC source code from Tencent,
// please note that tRPC source code is licensed under the Apache 2.0 License,
// A copy of the Apache 2.0 License is included in this file.
//
//
package dsn
import (
"errors"
"strings"
)
// URIHostExtractor extracts host from URI, used for ip resolve(like get ip from polaris), work with ResolvableSelector
type URIHostExtractor struct {
}
// Extract extracts host from uri.
// Note: The uri has been preprocessed, no longer contains the strings preceding :// and ://.
func (e *URIHostExtractor) Extract(uri string) (int, int, error) {
// mongodb+polaris://user:[email protected]
offset := 0
// beginning of the host
if idx := strings.LastIndex(uri, "@"); idx != -1 {
uri = uri[idx+1:]
offset += idx + 1
}
// resolve end-part of the host
begin := offset
length, err := dealHostEndPart(uri)
if err != nil {
return 0, 0, err
}
uri = uri[0:length]
return e.dealProtocolToken(uri, begin, length)
}
func dealHostEndPart(uri string) (int, error) {
length := len(uri)
if idx := strings.IndexAny(uri, "/?@"); idx != -1 {
if uri[idx] == '@' {
return 0, errors.New("parse host from uri: unescaped @ sign in user info")
}
if uri[idx] == '?' {
return 0, errors.New("parse host from uri: must have a / before the query ?")
}
length = idx
}
return length, nil
}
func (e *URIHostExtractor) dealProtocolToken(uri string, begin, length int) (int, int, error) {
begin, length = dealProtocolPrefix(uri, begin, length)
length = dealProtocolSuffix(uri, length)
return begin, length, nil
}
func dealProtocolPrefix(uri string, begin, length int) (int, int) {
if strings.HasPrefix(uri, "tcp(") {
return begin + 4, length - 4
}
return begin, length
}
func dealProtocolSuffix(uri string, length int) int {
if strings.HasSuffix(uri, ")") {
return length - 1
}
return length
}