-
Notifications
You must be signed in to change notification settings - Fork 0
/
gomsf.go
93 lines (77 loc) · 1.49 KB
/
gomsf.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
package gomsf
import (
"bytes"
"fmt"
"net/http"
"time"
"github.com/imroc/req"
msgpack "github.com/vmihailenco/msgpack/v5"
)
type Generic struct {
Restult string `msgpack:"result"`
}
type MsfGo struct {
baseurl string
headers http.Header
httpcli *req.Req
}
type MsfCli interface {
Send([]string, interface{}) error
}
type Opt func(msfGo *MsfGo)
func WithDebug(debug bool) Opt {
return func(msfGo *MsfGo) {
if debug == true {
req.Debug = true
return
}
req.Debug = false
}
}
func WithSkipVerify(ssl bool) Opt {
return func(msfGo *MsfGo) {
msfGo.httpcli.EnableInsecureTLS(ssl)
}
}
func WithTimeOut(tm time.Duration) Opt {
return func(msfGo *MsfGo) {
msfGo.httpcli.SetTimeout(tm)
}
}
func NewMsf(addr string, usessl bool, opts ...Opt) *MsfGo {
var msfdUrl string
rq := req.New()
if usessl {
msfdUrl = fmt.Sprintf("https://%s/api/1.0/", addr)
} else {
msfdUrl = fmt.Sprintf("http://%s/api/1.0/", addr)
}
msf := &MsfGo{
baseurl: msfdUrl,
httpcli: rq,
headers: http.Header{
"Content-Type": []string{"binary/message-pack"},
},
}
for _, v := range opts {
v(msf)
}
return msf
}
func (m *MsfGo) Send(sts []string, save interface{}) error {
var (
buf = bufpool.Get().(*bytes.Buffer)
err error
)
buf.Reset()
defer bufpool.Put(buf)
err = msgpack.NewEncoder(buf).Encode(sts)
if err != nil {
return err
}
resq, err := m.httpcli.Post(m.baseurl, m.headers, buf.Bytes())
if err != nil {
return err
}
return msgpack.Unmarshal(resq.Bytes(), &save)
}