-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathjsonapi_client.go
More file actions
98 lines (83 loc) · 2.01 KB
/
jsonapi_client.go
File metadata and controls
98 lines (83 loc) · 2.01 KB
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
package jsonapi
import (
"bytes"
"crypto"
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"io/ioutil"
"net/http"
"net/url"
"strconv"
)
type Request struct {
method string
reqObj *http.Request
reqJSON []byte
}
func Get(urlStr string, req interface{}) (*Request, error) {
return newRequest("GET", urlStr, req)
}
func Post(urlStr string, req interface{}) (*Request, error) {
return newRequest("POST", urlStr, req)
}
func newRequest(method, urlStr string, req interface{}) (*Request, error) {
reqJSON, err := json.Marshal(req)
if err != nil {
return nil, err
}
reqObj, err := http.NewRequest(method, urlStr, nil)
if err != nil {
return nil, err
}
return &Request{method, reqObj, reqJSON}, nil
}
func (r *Request) Signature(hash crypto.Hash, key string, time int) {
timeStr := strconv.Itoa(time)
sigData := signature(
hash,
[]byte(key),
[]byte(timeStr),
[]byte(r.reqObj.URL.Path),
r.reqJSON,
)
sigHead := base64.StdEncoding.EncodeToString(sigData)
r.reqObj.Header.Set("t", timeStr)
r.reqObj.Header.Set("s", sigHead)
}
func (r *Request) Do(client *http.Client, rsp interface{}) error {
r.reqObj.Header.Set("content-type", "application/json")
switch r.method {
case "GET":
r.reqObj.URL.RawQuery = url.QueryEscape(string(r.reqJSON))
case "POST":
r.reqObj.ContentLength = int64(len(r.reqJSON))
r.reqObj.Body = ioutil.NopCloser(bytes.NewReader(r.reqJSON))
default:
return errors.New("JsonAPI unsupported request method")
}
rspObj, err := client.Do(r.reqObj)
if err != nil {
return err
}
if rspObj.StatusCode == http.StatusInternalServerError {
rsp = new(JsonAPIError)
}
err = json.NewDecoder(rspObj.Body).Decode(rsp)
rspObj.Body.Close()
if err != nil {
return err
}
switch rspObj.StatusCode {
case http.StatusOK:
return nil
case http.StatusInternalServerError:
if e, ok := rsp.(*JsonAPIError); ok {
return fmt.Errorf("internal server error : %s", e.Err)
}
return errors.New("unknow error")
default:
return fmt.Errorf("unknow error code %d", rspObj.StatusCode)
}
}