-
Notifications
You must be signed in to change notification settings - Fork 4
/
payloads.go
93 lines (86 loc) · 2.57 KB
/
payloads.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
package limacharlie
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type Payload struct {
Name string `json:"name"`
Oid string `json:"oid"`
Size uint64 `json:"size"`
By string `json:"by"`
CreatedOn uint64 `json:"created"`
}
type payloadsList struct {
Payloads map[PayloadName]Payload `json:"payloads"`
}
type PayloadName = string
type payloadGetPointer struct {
URL string `json:"get_url"`
}
type payloadPutPointer struct {
URL string `json:"put_url"`
}
// List all the Payloads in an LC organization.
func (org Organization) Payloads() (map[PayloadName]Payload, error) {
resp := payloadsList{}
request := makeDefaultRequest(&resp)
if err := org.client.reliableRequest(http.MethodGet, fmt.Sprintf("payload/%s", org.client.options.OID), request); err != nil {
return nil, err
}
return resp.Payloads, nil
}
// Download the content of a Payload in an LC organization.
func (org Organization) Payload(name PayloadName) ([]byte, error) {
resp := payloadGetPointer{}
request := makeDefaultRequest(&resp)
if err := org.client.reliableRequest(http.MethodGet, fmt.Sprintf("payload/%s/%s", org.client.options.OID, name), request); err != nil {
return nil, err
}
httpResp, err := http.Get(resp.URL)
if err != nil {
return nil, err
}
defer httpResp.Body.Close()
data, err := ioutil.ReadAll(httpResp.Body)
if err != nil {
return nil, err
}
return data, nil
}
// Delete a Payload from within an LC organization.
func (org Organization) DeletePayload(name PayloadName) error {
resp := Dict{}
request := makeDefaultRequest(&resp)
if err := org.client.reliableRequest(http.MethodDelete, fmt.Sprintf("payload/%s/%s", org.client.options.OID, name), request); err != nil {
return err
}
return nil
}
// Create a Payload in an LC organization.
func (org Organization) CreatePayloadFromBytes(name PayloadName, data []byte) error {
return org.CreatePayloadFromReader(name, bytes.NewBuffer(data))
}
func (org Organization) CreatePayloadFromReader(name PayloadName, data io.Reader) error {
resp := payloadPutPointer{}
request := makeDefaultRequest(&resp)
if err := org.client.reliableRequest(http.MethodPost, fmt.Sprintf("payload/%s/%s", org.client.options.OID, name), request); err != nil {
return err
}
c := &http.Client{}
req, err := http.NewRequest(http.MethodPut, resp.URL, data)
if err != nil {
return err
}
req.Header.Set("Content-Type", "application/octet-stream")
httpResp, err := c.Do(req)
if err != nil {
return err
}
if httpResp.StatusCode != 200 {
return fmt.Errorf("failed to PUT payload, http status: %d", httpResp.StatusCode)
}
return nil
}