forked from notedit/janus-go
-
Notifications
You must be signed in to change notification settings - Fork 3
/
transport.go
88 lines (75 loc) · 1.54 KB
/
transport.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
package admin
import (
"bytes"
"encoding/json"
"fmt"
"io/ioutil"
"net"
"net/http"
"time"
)
type TransportError struct {
Code int
Msg string
}
func (e *TransportError) Error() string {
return fmt.Sprintf("[%d] %s", e.Code, e.Msg)
}
type Transport interface {
Request(APIRequest) (interface{}, error)
Close() error
}
type HttpTransport struct {
client *http.Client
url string
}
func NewHttpTransport(url string) *HttpTransport {
c := new(HttpTransport)
c.url = url
c.client = &http.Client{
Transport: &http.Transport{
DialContext: (&net.Dialer{
Timeout: 5 * time.Second,
}).DialContext,
TLSHandshakeTimeout: 5 * time.Second,
},
Timeout: 10 * time.Second,
}
return c
}
func (t *HttpTransport) Request(r APIRequest) (interface{}, error) {
b, err := json.Marshal(r.Payload())
if err != nil {
return nil, err
}
req, err := http.NewRequest(http.MethodPost, t.url+r.Endpoint(), bytes.NewBuffer(b))
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json; charset=utf-8")
resp, err := t.client.Do(req)
if err != nil {
return nil, err
}
if resp.StatusCode >= http.StatusBadRequest {
return nil, &TransportError{Code: resp.StatusCode, Msg: resp.Status}
}
defer resp.Body.Close()
body, err := ioutil.ReadAll(resp.Body)
if err != nil {
return nil, err
}
pResp, err := ParseAMResponse(r, body)
if err != nil {
return nil, err
}
switch pResp := pResp.(type) {
case error:
return nil, pResp
default:
return pResp, nil
}
}
func (t *HttpTransport) Close() error {
return nil
}