/
handleGetTicket.go
104 lines (89 loc) · 2.07 KB
/
handleGetTicket.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
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"path"
timod "github.com/thingsdb/go-timod"
"github.com/vmihailenco/msgpack"
)
type getTicketReq struct {
Sid string `msgpack:"sid"`
}
type getTicketRes struct {
Tickets []interface{}
}
func handleGetTicket(pkg *timod.Pkg) {
var req getTicketReq
err := msgpack.Unmarshal(pkg.Data, &req)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
"Failed to unpack get-ticket request. Expecting a SID (string)")
return
}
params := url.Values{}
params.Set("sid", req.Sid)
reqURL, err := url.Parse(cred.URI)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
fmt.Sprintf("Failed to parse URI (%s) (%s)", reqURL.String(), err))
return
}
reqURL.Path = path.Join(reqURL.Path, "ticket")
reqURL.RawQuery = params.Encode()
httpReq, err := http.NewRequest("GET", reqURL.String(), http.NoBody)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
fmt.Sprintf("Failed to create request (%s)", err))
return
}
httpReq.SetBasicAuth(cred.Login, cred.Password)
httpReq.Header.Set("Content-Type", "application/json")
// Do the actual API request
client := &http.Client{}
res, err := client.Do(httpReq)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExOperation,
fmt.Sprintf("Failed to perform the request (%s)", err))
return
}
// Read the body
resBody, err := ioutil.ReadAll(res.Body)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
fmt.Sprintf("Failed to read bytes from response (%s)", err))
return
}
// Check status code and return error if not 2XX
if res.StatusCode/100 != 2 {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
fmt.Sprintf("%s (%d)", string(resBody), res.StatusCode))
return
}
// Unpack the newTicket response
var response getTicketRes
err = json.Unmarshal(resBody, &response)
if err != nil {
timod.WriteEx(
pkg.Pid,
timod.ExBadData,
fmt.Sprintf("Failed to unpack response (%s)", err))
return
}
// Return the sid for the new ticket
timod.WriteResponse(pkg.Pid, &response.Tickets[0])
}