-
Notifications
You must be signed in to change notification settings - Fork 6
/
Copy pathlua.go
104 lines (83 loc) · 2.31 KB
/
lua.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
94
95
96
97
98
99
100
101
102
103
104
package luascript
import (
"bufio"
"context"
"fmt"
"github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/ext"
"github.com/traefik/traefik/v2/pkg/log"
"github.com/traefik/traefik/v2/pkg/tracing"
"net/http"
"os"
"github.com/yuin/gopher-lua"
"github.com/yuin/gopher-lua/parse"
config "github.com/traefik/traefik/v2/pkg/config/dynamic"
"github.com/traefik/traefik/v2/pkg/middlewares"
)
const (
typeName = "LuaScript"
)
// LuaScript middleware
type luaScript struct {
next http.Handler
name string
lfunc *lua.FunctionProto
}
// New creates a new handler.
func New(ctx context.Context, next http.Handler, config config.LuaScript, name string) (http.Handler, error) {
logger := log.FromContext(middlewares.GetLoggerCtx(ctx, name, typeName))
logger.Debug("Creating middleware")
var m *luaScript
lfunc, err := compileLua(config.Script)
if err != nil {
return nil, fmt.Errorf("error compile lua script '%s': %v", config.Script, err)
}
m = &luaScript{
next: next,
name: name,
lfunc: lfunc,
}
return m, nil
}
func (l *luaScript) GetTracingInformation() (string, ext.SpanKindEnum) {
return l.name, tracing.SpanKindNoneEnum
}
func (l *luaScript) ServeHTTP(rw http.ResponseWriter, req *http.Request) {
logger := log.FromContext(middlewares.GetLoggerCtx(req.Context(), l.name, typeName))
ctx := req.Context()
span := opentracing.SpanFromContext(ctx)
luaState := acquireLuaState(rw, req, logger)
defer releaseLuaState(luaState)
if err := doCompiledFile(luaState.L, l.lfunc); err != nil {
logger.Errorf("error run compiled lua script", "error", err)
span.SetTag("error", "true")
span.LogKV("message", "error run compiled lua script: " + err.Error())
return
}
if luaState.moduleTraefik.WasInterrupted() {
return
}
l.next.ServeHTTP(rw, req)
}
func doCompiledFile(L *lua.LState, proto *lua.FunctionProto) error {
lfunc := L.NewFunctionFromProto(proto)
L.Push(lfunc)
return L.PCall(0, lua.MultRet, nil)
}
func compileLua(filePath string) (*lua.FunctionProto, error) {
file, err := os.Open(filePath)
if err != nil {
return nil, err
}
defer file.Close()
reader := bufio.NewReader(file)
chunk, err := parse.Parse(reader, filePath)
if err != nil {
return nil, err
}
proto, err := lua.Compile(chunk, filePath)
if err != nil {
return nil, err
}
return proto, nil
}