-
Notifications
You must be signed in to change notification settings - Fork 17
/
Copy pathini.go
86 lines (75 loc) · 1.82 KB
/
ini.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
package main
import (
"context"
"crypto/tls"
"crypto/x509"
"errors"
"fmt"
"io"
"net/http"
"net/url"
"os"
ini "gopkg.in/ini.v1"
)
var (
errRedirectsDisallowed = errors.New("redirects disallowed")
errBadStatusCode = errors.New("bad HTTP status")
)
type iniConfig struct {
source string // URL or file path
options ini.LoadOptions
section string
headers httpHeadersFlag
skipTLSVerify bool
ca *x509.CertPool
}
func loadINISection(cfg iniConfig) (map[string]string, error) {
if cfg.source == "" {
return nil, nil //nolint:nilnil // TODO.
}
var data []byte
u, err := url.Parse(cfg.source)
if err == nil && u.IsAbs() {
data, err = fetchINI(cfg)
} else {
data, err = os.ReadFile(cfg.source)
}
if err != nil {
return nil, err
}
file, err := ini.LoadSources(cfg.options, data)
if err != nil {
return nil, err
}
return file.Section(cfg.section).KeysHash(), nil
}
func fetchINI(cfg iniConfig) (data []byte, err error) {
client := &http.Client{
Transport: &http.Transport{
Proxy: http.ProxyFromEnvironment,
TLSClientConfig: &tls.Config{
InsecureSkipVerify: cfg.skipTLSVerify, //nolint:gosec // TLS InsecureSkipVerify may be true.
RootCAs: cfg.ca,
},
},
CheckRedirect: func(*http.Request, []*http.Request) error {
return errRedirectsDisallowed
},
}
req, err := http.NewRequestWithContext(context.Background(), http.MethodGet, cfg.source, http.NoBody)
if err != nil {
return nil, err
}
for _, h := range cfg.headers {
req.Header.Add(h.name, h.value)
}
resp, err := client.Do(req) //nolint:bodyclose // False positive.
if err != nil {
return nil, err
}
defer warnIfFail(resp.Body.Close)
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("%w: %d", errBadStatusCode, resp.StatusCode)
}
return io.ReadAll(resp.Body)
}