forked from kenshaw/hilink
/
opts.go
116 lines (98 loc) · 2.41 KB
/
opts.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
113
114
115
116
package hilink
import (
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"net/http"
"net/http/httputil"
"net/url"
"strings"
)
// Option is an option used when creating a new Client.
type Option func(*Client) error
// URL is an option that handles setting the URL on the Client.
func URL(rawurl string) Option {
return func(c *Client) error {
var err error
if !strings.HasSuffix(rawurl, "/") {
rawurl += "/"
}
c.rawurl = rawurl
c.url, err = url.Parse(rawurl)
return err
}
}
func hashPw(text string) string {
h := sha256.New()
h.Write([]byte(text))
hash := hex.EncodeToString(h.Sum(nil))
return base64.StdEncoding.EncodeToString([]byte(hash))
}
// Auth is an option specifying the identifier and password to use.
// The option is ignored if id is an empty string.
func Auth(id, pw string) Option {
return func(c *Client) error {
if id != "" {
c.authID = id
c.authPW = pw
}
return nil
}
}
// HTTPClient is an option that allows setting the http.Client used by the
// Client.
func HTTPClient(client *http.Client) Option {
return func(c *Client) error {
c.client = client
return nil
}
}
// NoSessionStart is an option that prevents the automatic creation of a
// session with the Hilink device.
func NoSessionStart(c *Client) error {
c.nostart = true
return nil
}
// httpLogger handles logging http requests and responses.
type httpLogger struct {
transport http.RoundTripper
requestLogf, responseLogf func(string, ...interface{})
}
func (hl *httpLogger) RoundTrip(req *http.Request) (*http.Response, error) {
trans := hl.transport
if trans == nil {
trans = http.DefaultTransport
}
reqBody, err := httputil.DumpRequestOut(req, true)
if err != nil {
return nil, err
}
res, err := trans.RoundTrip(req)
if err != nil {
return nil, err
}
resBody, err := httputil.DumpResponse(res, true)
if err != nil {
return nil, err
}
hl.requestLogf("%s", string(reqBody))
hl.responseLogf("%s", string(resBody))
return res, err
}
// Log is an option that writes all HTTP request and response data to the
// respective logger.
func Log(requestLogf, responseLogf func(string, ...interface{})) Option {
return func(c *Client) error {
hl := &httpLogger{
requestLogf: requestLogf,
responseLogf: responseLogf,
}
// inject as client transport
c.transport = hl
if c.client != nil {
hl.transport = c.client.Transport
c.client.Transport = hl
}
return nil
}
}