-
Notifications
You must be signed in to change notification settings - Fork 0
/
common_web.go
81 lines (66 loc) · 1.61 KB
/
common_web.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
package godevman
import (
"crypto/tls"
"fmt"
"io/ioutil"
"net/http"
"net/http/cookiejar"
"time"
)
// Add additional default headers
type MyRoundTripper struct {
r http.RoundTripper
h map[string][]string
}
func (rt MyRoundTripper) RoundTrip(r *http.Request) (*http.Response, error) {
for k, v := range rt.h {
r.Header[k] = v
}
return rt.r.RoundTrip(r)
}
// Get authenticated web session
func (d *device) WebSession() *http.Client {
return d.webSession.client
}
// Create http client
func (d *device) webClient(headers map[string][]string) (*http.Client, error) {
// disable certificate check
tr := &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
}
// setup cookie jar
jar, err := cookiejar.New(nil)
if err != nil {
return nil, fmt.Errorf("got error while creating cookie jar %s", err.Error())
}
// return client
client := &http.Client{
Timeout: time.Second * 15,
Transport: MyRoundTripper{r: tr, h: headers},
Jar: jar,
}
return client, nil
}
// Make http Get request and return byte slice of body.
// Argument string should contain request parameters.
func (d *device) WebApiGet(params string) ([]byte, error) {
client := d.webSession.client
if d.webSession.client == nil {
// setup client
c, err := d.webClient(nil)
if err != nil {
return nil, err
}
client = c
}
res, err := client.Get("https://" + d.ip + "/" + params)
if err != nil {
return nil, err
}
defer res.Body.Close()
body, _ := ioutil.ReadAll(res.Body)
if res.StatusCode > 299 {
return body, fmt.Errorf("response failed with status code: %d", res.StatusCode)
}
return body, nil
}