forked from 17media/zencoder
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathzencoder.go
108 lines (87 loc) · 2.05 KB
/
zencoder.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
package zencoder
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"io/ioutil"
"net/http"
)
type Zencoder struct {
BaseUrl string
Header http.Header
Client *http.Client
}
func NewZencoder(apiKey string) *Zencoder {
return &Zencoder{
Client: http.DefaultClient,
BaseUrl: "https://app.zencoder.com/api/v2/",
Header: http.Header{
"Content-Type": []string{"application/json"},
"Accept": []string{"application/json"},
"Zencoder-Api-Key": []string{apiKey},
"User-Agent": []string{"gozencoder v1"},
},
}
}
func (z *Zencoder) call(method, path string, request interface{}, expectedStatus []int) (*http.Response, error) {
var buffer io.Reader
if request != nil {
b, err := json.Marshal(request)
if err != nil {
return nil, err
}
buffer = bytes.NewBuffer(b)
}
req, err := http.NewRequest(method, fmt.Sprintf("%s/%s", z.BaseUrl, path), buffer)
if err != nil {
return nil, err
}
req.Header = z.Header
resp, err := z.Client.Do(req)
if err != nil {
return resp, err
}
for _, status := range expectedStatus {
if resp.StatusCode == status {
return resp, err
}
}
return nil, errors.New(resp.Status)
}
func (z *Zencoder) post(path string, request interface{}, response interface{}) error {
resp, err := z.call("POST", path, request, []int{http.StatusCreated, http.StatusOK})
if err != nil {
return err
}
if err := UnmarshalBody(resp.Body, response); err != nil {
return err
}
return nil
}
func (z *Zencoder) putNoContent(path string) error {
_, err := z.call("PUT", path, nil, []int{http.StatusNoContent})
if err != nil {
return err
}
return nil
}
func (z *Zencoder) getBody(path string, response interface{}) error {
resp, err := z.call("GET", path, nil, []int{http.StatusOK})
if err != nil {
return err
}
if err := UnmarshalBody(resp.Body, response); err != nil {
return err
}
return nil
}
func UnmarshalBody(body io.ReadCloser, result interface{}) error {
defer body.Close()
b, err := ioutil.ReadAll(body)
if err != nil {
return err
}
return json.Unmarshal(b, result)
}