-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathnats.go
46 lines (37 loc) · 851 Bytes
/
nats.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
package lua
import (
"fmt"
"github.com/nats-io/nats.go"
"github.com/yuin/gopher-lua"
)
var nc *nats.Conn
// Preload adds the NATS module to the given Lua state.
func PreloadNats(L *lua.LState, conn *nats.Conn) {
L.PreloadModule("nats", natsLoader)
nc = conn
}
func natsLoader(L *lua.LState) int {
mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
"publish": natsPublish,
})
L.Push(mod)
return 1
}
func natsPublish(L *lua.LState) int {
if nc == nil {
L.Push(lua.LBool(false))
L.Push(lua.LString("Not connected to NATS"))
return 2
}
subject := L.ToString(1)
message := L.ToString(2)
err := nc.Publish(subject, []byte(message))
if err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(fmt.Sprintf("Failed to publish message: %v", err)))
return 2
}
L.Push(lua.LBool(true))
L.Push(lua.LNil)
return 2
}