forked from blockwatch-cc/tzstats-go
-
Notifications
You must be signed in to change notification settings - Fork 0
/
params.go
96 lines (87 loc) · 1.64 KB
/
params.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
// Copyright (c) 2020-2022 Blockwatch Data Inc.
// Author: alex@blockwatch.cc
package tzstats
import (
"fmt"
"net/url"
// "strconv"
"strings"
)
type Params struct {
Server string
Prefix string
Query url.Values
}
func NewParams() Params {
return Params{
Query: url.Values{},
}
}
func (p Params) Check() error {
if p.Server == "" {
return fmt.Errorf("empty server URL")
}
return nil
}
func (p Params) Copy() Params {
np := NewParams()
np.Server = p.Server
np.Prefix = p.Prefix
for n, v := range p.Query {
np.Query[n] = v
}
return np
}
func (p Params) AppendQuery(path string) string {
if len(p.Query) > 0 {
return path + "?" + p.Query.Encode()
}
return path
}
func (p Params) Url(actions ...string) string {
fields := make([]string, 0, 4)
fields = append(fields, p.Server)
if p.Prefix != "" {
fields = append(fields, p.Prefix)
}
if len(actions) > 0 {
for _, v := range actions {
fields = append(fields, strings.Trim(v, "/"))
}
}
if len(p.Query) == 0 {
return strings.Join(fields, "/")
}
return strings.Join([]string{
strings.Join(fields, "/"),
p.Query.Encode(),
}, "?")
}
// parse from
// http://server:port/prefix
// server:port/prefix
// server/prefix
// /prefix
func ParseParams(urlString string) (Params, error) {
p := NewParams()
if !strings.HasPrefix(urlString, "http") {
urlString = "https://" + urlString
}
u, err := url.Parse(urlString)
if err != nil {
return p, err
}
p.Query = u.Query()
if u.Scheme == "" {
u.Scheme = "https"
}
if u.Path != "" {
p.Prefix = strings.Trim(u.Path, "/")
}
u.RawQuery = ""
u.Fragment = ""
u.Path = ""
u.RawPath = ""
p.Server = u.String()
return p, nil
}