-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathapi.go
More file actions
97 lines (87 loc) · 1.84 KB
/
api.go
File metadata and controls
97 lines (87 loc) · 1.84 KB
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
package redis
import (
"github.com/gomodule/redigo/redis"
lua "github.com/yuin/gopher-lua"
)
const (
// max idle connections
MaxIdleConns = 1
// max open connections
MaxOpenConns = 1
)
type lRedis interface {
constructor(string, int) (lRedis, error)
getPool() *redis.Pool
}
var redisDB = new(luaRedis)
func Open(L *lua.LState) int {
conn := L.CheckString(1)
db := L.CheckInt(2)
result, err := redisDB.constructor(conn, db)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
ud := L.NewUserData()
ud.Value = result
L.SetMetatable(ud, L.GetTypeMetatable(`redis_ud`))
L.Push(ud)
return 1
}
func checkRedis(L *lua.LState, n int) lRedis {
ud := L.CheckUserData(n)
if v, ok := ud.Value.(lRedis); ok {
return v
}
L.ArgError(n, "redis expected")
return nil
}
func Do(L *lua.LState) int {
dbInterface := checkRedis(L, 1)
cmd := L.CheckString(2)
arg := L.CheckTable(3)
redisArg := make([]interface{}, 0)
arg.ForEach(func(k lua.LValue, v lua.LValue) {
switch v.(type) {
case lua.LString:
redisArg = append(redisArg, string(v.(lua.LString)))
case lua.LNumber:
redisArg = append(redisArg, float64(v.(lua.LNumber)))
}
})
redisPool := dbInterface.getPool()
conn := redisPool.Get()
defer conn.Close()
reply, err := conn.Do(cmd, redisArg...)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
var rows *lua.LTable
if v, ok := reply.([]interface{}); ok {
rows, err = parseReplys(v, L)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(rows)
} else {
lv, err := parseReply(reply, L)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(lv)
}
return 1
}
func Close(L *lua.LState) int {
dbInterface := checkRedis(L, 1)
pool := dbInterface.getPool()
pool.Close()
return 0
}