/
HttpBackend.go
129 lines (98 loc) · 2.52 KB
/
HttpBackend.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
126
127
128
129
package backends
import (
"bytes"
"errors"
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"strconv"
"time"
//"gopkg.in/yaml.v2"
)
type HttpBackend struct {
DefaultTimeout int `json:"default_timeout" bson:"default_timeout" yaml:"default_timeout" hcl:"default_timeout"`
}
func (b *HttpBackend) Get(url string, contentType string, timeout int) ([]byte, error) {
client := &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
req, err := http.NewRequest("GET", url, nil)
if err != nil {
return []byte{}, err
}
req.Header.Set("content-type", contentType)
resp, err := client.Do(req)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
if resp.StatusCode != 200 {
return resp_body, errors.New("Backend returned status code "+strconv.Itoa(resp.StatusCode)+".\n"+string(resp_body))
}
return resp_body, nil
}
func (b *HttpBackend) Post(url string, contentType string, data []byte, timeout int) ([]byte, error) {
client := &http.Client{
Timeout: time.Duration(timeout) * time.Second,
}
req, err := http.NewRequest("POST", url, bytes.NewBuffer(data))
if err != nil {
return []byte{}, err
}
req.Header.Set("content-type", contentType)
resp, err := client.Do(req)
if err != nil {
return []byte{}, err
}
defer resp.Body.Close()
resp_body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return []byte{}, err
}
if resp.StatusCode != 200 {
return resp_body, errors.New("Backend returned status code "+strconv.Itoa(resp.StatusCode)+".\n"+string(resp_body))
}
return resp_body, nil
}
func (b *HttpBackend) GetJson(u string, target interface{}) error {
resp_body, err := b.Get(u, "application/json", b.DefaultTimeout)
if err != nil {
return err
}
err = json.Unmarshal(resp_body, target)
if err != nil {
return err
}
return nil
}
func (b *HttpBackend) PostJson(u string, data map[string]interface{}, target interface{}) error {
req_body, err := json.Marshal(data)
if err != nil {
return err
}
//fmt.Println("Request Body")
//req_yml, err := yaml.Marshal(data)
//if err != nil {
// return err
//}
//fmt.Println(string(req_yml))
resp_body, err := b.Post(u, "application/json", req_body, b.DefaultTimeout)
if err != nil {
return err
}
fmt.Println("Response Body")
fmt.Println(len(resp_body))
fmt.Println(string(resp_body))
if len(resp_body) > 0 {
err = json.Unmarshal(resp_body, target)
if err != nil {
return err
}
}
return nil
}