-
Notifications
You must be signed in to change notification settings - Fork 1
/
tshttpclient.go
125 lines (102 loc) · 2.4 KB
/
tshttpclient.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
117
118
119
120
121
122
123
124
125
package go_ts3
import (
"encoding/json"
"fmt"
"github.com/asaskevich/EventBus"
"github.com/jkoenig134/schema"
"github.com/valyala/fasthttp"
)
type Config struct {
baseUrl string
apiKey string
}
func NewConfig(baseUrl string, apiKey string) Config {
return Config{
baseUrl: baseUrl,
apiKey: apiKey,
}
}
type TeamspeakHttpClient struct {
config Config
httpClient fasthttp.Client
eventBus EventBus.Bus
encoder schema.Encoder
serverID int
eventClient *EventClient
}
func (c *TeamspeakHttpClient) SetServerID(serverID int) {
c.serverID = serverID
if c.eventClient != nil {
_ = c.eventClient.SwitchServer(serverID)
}
}
func NewClient(config Config) TeamspeakHttpClient {
return TeamspeakHttpClient{
config,
fasthttp.Client{},
EventBus.New(),
*schema.NewEncoder(),
1,
nil,
}
}
type status struct {
Code int `json:"code"`
Message string `json:"message"`
}
type tsResponse struct {
Body interface{} `json:"body"`
Status status `json:"status"`
}
func (t *tsResponse) asError() error {
return fmt.Errorf(
"Query returned non 0 exit code: '%d'. Message: '%s' ",
t.Status.Code,
t.Status.Message)
}
func (c *TeamspeakHttpClient) requestWithParams(path string, paramStruct interface{}, v interface{}) error {
param, err := c.encodeStruct(paramStruct)
if err != nil {
return err
}
merged := fmt.Sprintf("%s%s", path, param)
return c.request(merged, v)
}
func (c *TeamspeakHttpClient) request(path string, v interface{}) error {
requestUrl := fmt.Sprintf("%s/%d/%s", c.config.baseUrl, c.serverID, path)
request := fasthttp.AcquireRequest()
request.Header.Set("x-api-key", c.config.apiKey)
request.SetRequestURI(requestUrl)
defer fasthttp.ReleaseRequest(request)
response := fasthttp.AcquireResponse()
defer fasthttp.ReleaseResponse(response)
err := c.httpClient.Do(request, response)
if err != nil {
return err
}
stringBody := string(response.Body())
code := response.StatusCode()
if code != 200 {
err = fmt.Errorf("Error Code: %d\n%s", code, stringBody)
return err
}
tsResponse := &tsResponse{}
err = json.Unmarshal(response.Body(), tsResponse)
if err != nil {
return err
}
if tsResponse.Status.Code != 0 {
return tsResponse.asError()
}
if v == nil {
return nil
}
jsonBody, err := json.Marshal(tsResponse.Body)
if err != nil {
return err
}
if err = json.Unmarshal(jsonBody, v); err != nil {
return err
}
return nil
}