-
Notifications
You must be signed in to change notification settings - Fork 18
/
dsn.go
112 lines (95 loc) · 2.04 KB
/
dsn.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
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
package uptrace
import (
"fmt"
"net"
"net/url"
)
type DSN struct {
original string
Scheme string
Host string
HTTPPort string
GRPCPort string
Token string
}
func (dsn *DSN) String() string {
return dsn.original
}
func (dsn *DSN) SiteURL() string {
if dsn.Host == "uptrace.dev" {
return "https://app.uptrace.dev"
}
return dsn.Scheme + "://" + joinHostPort(dsn.Host, dsn.HTTPPort)
}
func (dsn *DSN) OTLPGrpcEndpoint() string {
if dsn.Host == "uptrace.dev" {
return "otlp.uptrace.dev:4317"
}
return joinHostPort(dsn.Host, dsn.GRPCPort)
}
func (dsn *DSN) OTLPHttpEndpoint() string {
if dsn.Host == "uptrace.dev" {
return "otlp.uptrace.dev:443"
}
return joinHostPort(dsn.Host, dsn.HTTPPort)
}
func ParseDSN(dsnStr string) (*DSN, error) {
if dsnStr == "" {
return nil, fmt.Errorf("DSN is empty (use WithDSN or UPTRACE_DSN env var)")
}
u, err := url.Parse(dsnStr)
if err != nil {
return nil, fmt.Errorf("can't parse DSN=%q: %s", dsnStr, err)
}
if u.Scheme == "" {
return nil, fmt.Errorf("DSN=%q does not have a scheme", dsnStr)
}
if u.Host == "" {
return nil, fmt.Errorf("DSN=%q does not have a host", dsnStr)
}
if u.User == nil {
return nil, fmt.Errorf("DSN=%q does not have a token", dsnStr)
}
dsn := DSN{
original: dsnStr,
Scheme: u.Scheme,
Host: u.Host,
Token: u.User.Username(),
}
if host, port, err := net.SplitHostPort(u.Host); err == nil {
dsn.Host = host
dsn.HTTPPort = port
}
if dsn.Host == "api.uptrace.dev" {
dsn.Host = "uptrace.dev"
}
if dsn.HTTPPort == "" {
switch dsn.Scheme {
case "http":
dsn.HTTPPort = "80"
case "https":
dsn.HTTPPort = "443"
}
}
query := u.Query()
if grpc := query.Get("grpc"); grpc != "" {
dsn.GRPCPort = grpc
}
if dsn.GRPCPort == "" {
if dsn.HTTPPort != "" {
dsn.GRPCPort = dsn.HTTPPort
if dsn.HTTPPort == "14317" {
dsn.HTTPPort = "14318"
}
} else {
dsn.GRPCPort = "4317"
}
}
return &dsn, nil
}
func joinHostPort(host, port string) string {
if port == "" {
return host
}
return net.JoinHostPort(host, port)
}