-
Notifications
You must be signed in to change notification settings - Fork 2
/
httpjson.go
57 lines (45 loc) · 1.18 KB
/
httpjson.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
package transport
import (
"bytes"
"encoding/json"
"errors"
"fmt"
ptypes "github.com/function61/eventhorizon/pusher/types"
"io/ioutil"
"net/http"
)
// transports Pushes via HTTP+JSON
type HttpJsonTransport struct {
address string
}
func NewHttpJsonTransport(address string) *HttpJsonTransport {
return &HttpJsonTransport{
address: address,
}
}
func (h *HttpJsonTransport) Push(input *ptypes.PushInput) (*ptypes.PushOutput, error) {
requestBody, err := json.Marshal(input)
if err != nil {
return nil, err
}
req, _ := http.NewRequest("POST", h.address, bytes.NewBuffer(requestBody))
// req.Header.Set("Authorization", fmt.Sprintf("Bearer %s", "foo"))
client := &http.Client{}
resp, networkErr := client.Do(req)
if networkErr != nil { // this is only network level errors
return nil, networkErr
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
errorBody, _ := ioutil.ReadAll(resp.Body)
return nil, errors.New(fmt.Sprintf(
"HTTP %s: %s",
resp.Status,
string(errorBody)))
}
var decodedResponse ptypes.PushOutput
if err := json.NewDecoder(resp.Body).Decode(&decodedResponse); err != nil {
return nil, err
}
return &decodedResponse, nil
}