forked from xjing521/gohessian
/
request.go
78 lines (67 loc) · 1.56 KB
/
request.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 gohessian
import (
"bytes"
"fmt"
"github.com/chenluyj/gohessian/util"
"io"
"io/ioutil"
"net/http"
)
type hessianRequest struct {
body []byte
}
//向hessian服务发请求,并将解析结果返回
//url string hessian 服务地址
//method string hessian 公开的方法
//params ...Any 请求参数
func Request(url string, method string, params ...Any) (interface{}, error) {
r := &hessianRequest{}
r.packHead(method)
for _, v := range params {
r.packParam(v)
}
r.packEnd()
resp, err := httpPost(url, bytes.NewReader(r.body))
if err != nil {
return nil, err
}
h := NewHessian(bytes.NewReader(resp))
v, err := h.Parse()
if err != nil {
return nil, err
}
return v, nil
}
//http post 请求,返回body字节数组
func httpPost(url string, body io.Reader) (rb []byte, err error) {
var resp *http.Response
if resp, err = http.Post(url, "application/binary", body); err != nil {
return nil, err
}
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf(resp.Status)
return
}
defer resp.Body.Close()
rb, err = ioutil.ReadAll(resp.Body)
return
}
//封装 hessian 请求头
func (h *hessianRequest) packHead(method string) {
tmp_b, _ := util.PackUint16(uint16(len(method)))
h.body = append(h.body, []byte{99, 0, 1, 109}...)
h.body = append(h.body, tmp_b...)
h.body = append(h.body, []byte(method)...)
}
//封装参数
func (h *hessianRequest) packParam(p Any) {
tmp_b, err := Encode(p)
if err != nil {
panic(err)
}
h.body = append(h.body, tmp_b...)
}
//封装包尾
func (h *hessianRequest) packEnd() {
h.body = append(h.body, 'z')
}