/
client.go
68 lines (56 loc) · 1.36 KB
/
client.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
package glua
import (
"fmt"
"io/ioutil"
"net/http"
"github.com/yuin/gopher-lua"
"github.com/go-gophers/gophers"
)
type client struct {
c *http.Client
}
func NewClient(c *http.Client) *client {
return &client{
c: c,
}
}
func (c *client) Loader(state *lua.LState) int {
module := state.SetFuncs(state.NewTable(), map[string]lua.LGFunction{
"get": c.get,
})
requestRegister(module, state)
responseRegister(module, state)
state.Push(module)
return 1
}
func (c *client) get(state *lua.LState) int {
return c.doAndPush(state, "GET", state.ToString(1), state.ToTable(2))
}
func (c *client) doAndPush(state *lua.LState, method string, url string, options *lua.LTable) int {
response, err := c.do(state, method, url, options)
if err != nil {
state.Push(lua.LNil)
state.Push(lua.LString(fmt.Sprintf("%s", err)))
return 2
}
state.Push(response)
return 1
}
func (c *client) do(state *lua.LState, method string, url string, options *lua.LTable) (*lua.LUserData, error) {
// TODO use Client.NewRequest
r, err := http.NewRequest(method, url, nil)
if err != nil {
return nil, err
}
req := &gophers.Request{Request: r}
var body []byte
resp, err := c.c.Do(req.Request)
if resp != nil {
body, err = ioutil.ReadAll(resp.Body)
resp.Body.Close()
}
if err != nil {
return nil, err
}
return responseNew(&gophers.Response{Response: resp}, body, state), nil
}