/
client.go
100 lines (86 loc) · 2.57 KB
/
client.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
package mock
import (
"context"
"crypto/tls"
"fmt"
"io/ioutil"
"net"
"net/http"
"net/http/httptest"
"os"
"path/filepath"
"strings"
)
const ACCESS_TOKEN = "abc123"
type MockServer struct {
Server *httptest.Server
mux *http.ServeMux
testdataPath string
}
func checkAuthorization(r *http.Request) bool {
return r.Header.Get("Authorization") == fmt.Sprintf("Bearer %s", ACCESS_TOKEN)
}
func getTestDataPath() string {
dir, _ := os.Getwd()
parts := strings.Split(dir, string(filepath.Separator))
i := 0
for i = 0; i < len(parts); i++ {
if parts[i] == "awair-exporter" {
break
}
}
return fmt.Sprintf("%c%s", filepath.Separator, filepath.Join(parts[0:i+1]...))
}
func NewMockServer() *MockServer {
m := &MockServer{}
m.mux = http.NewServeMux()
m.mux.Handle("/v1/users/self/devices", m.checkAuthMiddleware(m.serveFile("Devices.json")))
m.mux.Handle("/v1/users/self", m.checkAuthMiddleware(m.serveFile("UserInfo.json")))
m.mux.Handle("/v1/users/self/devices/", m.checkAuthMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/awair/0/air-data/latest") {
m.serveFile("UserLatestAirData-awair-0.json").ServeHTTP(w, r)
} else if strings.HasSuffix(r.URL.Path, "/awair-r2/0/air-data/latest") {
m.serveFile("UserLatestAirData-awair-r2-0.json").ServeHTTP(w, r)
} else if strings.HasSuffix(r.URL.Path, "/api-usages") {
m.serveFile("DeviceAPIUsage.json").ServeHTTP(w, r)
} else {
w.WriteHeader(404)
}
})))
m.testdataPath = filepath.Join(getTestDataPath(), "testdata")
m.Server = httptest.NewTLSServer(m.mux)
return m
}
func (m *MockServer) Close() {
m.Server.Close()
}
func (m *MockServer) Client() *http.Client {
return &http.Client{
Transport: &http.Transport{
DialContext: func(_ context.Context, network, _ string) (net.Conn, error) {
return net.Dial(network, m.Server.Listener.Addr().String())
},
TLSClientConfig: &tls.Config{
InsecureSkipVerify: true,
},
},
}
}
func (m *MockServer) checkAuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if !checkAuthorization(r) {
w.WriteHeader(403)
return
}
next.ServeHTTP(w, r)
})
}
func (m *MockServer) serveFile(path string) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
data, _ := ioutil.ReadFile(filepath.Join(m.testdataPath, path))
w.Header().Set("Content-Length", fmt.Sprintf("%d", len(data)))
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
w.Write([]byte(data))
})
}