/
http.go
47 lines (37 loc) · 1.24 KB
/
http.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
package alchemyapi
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"net/url"
)
var apiBase = "http://gateway-a.watsonplatform.net/"
type apiConnection interface {
get(endPoint string, params url.Values, config *config) ([]byte, error)
post(endPoint string, params url.Values, postData io.Reader, config *config) ([]byte, error)
}
// http interface
type httpImp struct {
}
func (h *httpImp) get(endPoint string, params url.Values, config *config) ([]byte, error) {
return h.connection("GET", endPoint, params, nil, config)
}
func (h *httpImp) post(endPoint string, params url.Values, postData io.Reader, config *config) ([]byte, error) {
return h.connection("POST", endPoint, params, postData, config)
}
func (h *httpImp) connection(method string, endPoint string, params url.Values, postData io.Reader, config *config) ([]byte, error) {
if config == nil || config.apikey == "" {
return make([]byte, 0), fmt.Errorf("No auth token")
}
params.Add("apikey", config.apikey)
params.Add("outputMode", "json")
req, _ := http.NewRequest(method, apiBase+endPoint, postData)
req.URL.RawQuery = params.Encode()
resp, err := http.DefaultClient.Do(req)
if err != nil {
return make([]byte, 0), err
}
defer resp.Body.Close()
return ioutil.ReadAll(resp.Body)
}