-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathservice.go
78 lines (64 loc) · 1.56 KB
/
service.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
package algolia
import (
"bytes"
"encoding/json"
"net/http"
"net/url"
)
type Service struct {
appId string
apiKey string
httpClient *http.Client
}
func (s *Service) newRequest(m, u string, obj interface{}) (*http.Request, error) {
b := new(bytes.Buffer)
if obj != nil {
if err := json.NewEncoder(b).Encode(obj); err != nil {
return nil, err
}
}
req, err := http.NewRequest(m, u, b)
if err != nil {
return nil, err
}
req.Header.Set("X-Algolia-Application-Id", s.appId)
req.Header.Set("X-Algolia-API-Key", s.apiKey)
req.Header.Set("Content-Type", "application/json")
return req, nil
}
func (s *Service) makeRequest(m string, u *url.URL, obj interface{}) *httpValue {
req, err := s.newRequest(m, u.String(), obj)
if err != nil {
return NewErrValue(err)
}
resp, err := s.httpClient.Do(req)
if err != nil {
return NewErrValue(err)
}
return NewValue(resp)
}
func (s *Service) Get(pth string) *httpValue {
u := &url.URL{
Scheme: "https",
Host: s.appId + "-dsn.algolia.net",
Path: pth,
}
return s.makeRequest("GET", u, nil)
}
func (s *Service) Post(pth string, obj interface{}) *httpValue {
return s.writeRequest("POST", pth, obj)
}
func (s *Service) Put(pth string, obj interface{}) *httpValue {
return s.writeRequest("PUT", pth, obj)
}
func (s *Service) Delete(pth string) *httpValue {
return s.writeRequest("DELETE", pth, nil)
}
func (s *Service) writeRequest(m, pth string, obj interface{}) *httpValue {
u := &url.URL{
Scheme: "https",
Host: s.appId + ".algolia.net",
Path: pth,
}
return s.makeRequest(m, u, obj)
}