forked from CodisLabs/codis
-
Notifications
You must be signed in to change notification settings - Fork 0
/
api.go
207 lines (183 loc) · 4.07 KB
/
api.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
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
// Copyright 2016 CodisLabs. All Rights Reserved.
// Licensed under the MIT (MIT-LICENSE.txt) license.
package rpc
import (
"bytes"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"net"
"net/http"
"net/url"
"strconv"
"time"
"github.com/ducesoft/codis/pkg/utils/errors"
"github.com/ducesoft/codis/pkg/utils/log"
"github.com/ducesoft/codis/pkg/utils/sync2/atomic2"
"github.com/ducesoft/codis/pkg/utils/trace"
)
const (
MethodGet = "GET"
MethodPut = "PUT"
MethodPost = "POST"
)
var client *http.Client
func init() {
var dials atomic2.Int64
tr := &http.Transport{}
tr.Dial = func(network, addr string) (net.Conn, error) {
c, err := net.DialTimeout(network, addr, time.Second)
if err == nil {
log.Debugf("rpc: dial new connection to [%d] %s - %s",
dials.Incr()-1, network, addr)
}
return c, err
}
client = &http.Client{
Transport: tr,
Timeout: time.Minute,
}
go func() {
for {
time.Sleep(time.Minute)
tr.CloseIdleConnections()
}
}()
}
type RemoteError struct {
Cause string
Stack trace.Stack
}
func (e *RemoteError) Error() string {
return e.Cause
}
func (e *RemoteError) TracedError() error {
return &errors.TracedError{
Cause: errors.New("[Remote Error] " + e.Cause),
Stack: e.Stack,
}
}
func NewRemoteError(err error) *RemoteError {
if err == nil {
return nil
}
if v, ok := err.(*RemoteError); ok {
return v
}
return &RemoteError{
Cause: err.Error(),
Stack: errors.Stack(err),
}
}
func responseBodyAsBytes(rsp *http.Response) ([]byte, error) {
b, err := ioutil.ReadAll(rsp.Body)
if err != nil {
return nil, errors.Trace(err)
}
return b, nil
}
func responseBodyAsError(rsp *http.Response) (error, error) {
b, err := responseBodyAsBytes(rsp)
if err != nil {
return nil, err
}
if len(b) == 0 {
return nil, errors.Errorf("remote error is empty")
}
e := &RemoteError{}
if err := json.Unmarshal(b, e); err != nil {
return nil, errors.Trace(err)
}
return e.TracedError(), nil
}
func apiMarshalJson(v interface{}) ([]byte, error) {
return json.MarshalIndent(v, "", " ")
}
func apiRequestJson(method string, url string, args, reply interface{}) error {
var body []byte
if args != nil {
b, err := apiMarshalJson(args)
if err != nil {
return errors.Trace(err)
}
body = b
}
req, err := http.NewRequest(method, url, bytes.NewReader(body))
if err != nil {
return errors.Trace(err)
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Content-Length", strconv.Itoa(len(body)))
}
var start = time.Now()
rsp, err := client.Do(req)
if err != nil {
return errors.Trace(err)
}
defer func() {
io.Copy(ioutil.Discard, rsp.Body)
rsp.Body.Close()
log.Debugf("call rpc [%s] %s in %v", method, url, time.Since(start))
}()
switch rsp.StatusCode {
case 200:
b, err := responseBodyAsBytes(rsp)
if err != nil {
return err
}
if reply == nil {
return nil
}
if err := json.Unmarshal(b, reply); err != nil {
return errors.Trace(err)
} else {
return nil
}
case 800, 1500:
e, err := responseBodyAsError(rsp)
if err != nil {
return err
} else {
return e
}
default:
return errors.Errorf("[%d] %s - %s", rsp.StatusCode, http.StatusText(rsp.StatusCode), url)
}
}
func ApiGetJson(url string, reply interface{}) error {
return apiRequestJson(MethodGet, url, nil, reply)
}
func ApiPutJson(url string, args, reply interface{}) error {
return apiRequestJson(MethodPut, url, args, reply)
}
func ApiPostJson(url string, args interface{}) error {
return apiRequestJson(MethodPost, url, args, nil)
}
func ApiResponseError(err error) (int, string) {
if err == nil {
return 800, ""
}
b, err := apiMarshalJson(NewRemoteError(err))
if err != nil {
return 800, ""
} else {
return 800, string(b)
}
}
func ApiResponseJson(v interface{}) (int, string) {
b, err := apiMarshalJson(v)
if err != nil {
return ApiResponseError(errors.Trace(err))
} else {
return 200, string(b)
}
}
func EncodeURL(host string, format string, args ...interface{}) string {
var u url.URL
u.Scheme = "http"
u.Host = host
u.Path = fmt.Sprintf(format, args...)
return u.String()
}