This repository has been archived by the owner on Feb 27, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 7
/
handler.go
92 lines (77 loc) · 2.15 KB
/
handler.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
package lua
import (
"fmt"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/caddyserver/caddy-lua/interpreter"
"github.com/mholt/caddy/middleware"
"github.com/yuin/gopher-lua"
"github.com/yuin/gopher-lua/parse"
)
type Handler struct {
Next middleware.Handler
Rules []Rule
Root string // site root
FileSys http.FileSystem
}
func (h Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) (int, error) {
for _, rule := range h.Rules {
if !middleware.Path(r.URL.Path).Matches(rule.BasePath) {
continue
}
// Check for index file
fpath := r.URL.Path
if idx, ok := middleware.IndexFile(h.FileSys, fpath, middleware.IndexPages); ok {
fpath = idx
}
// TODO: Check extension. If .lua, assume whole file is Lua script.
fileName := filepath.Join(h.Root, fpath)
file, err := h.FileSys.Open(fileName)
if err != nil {
if os.IsNotExist(err) {
return http.StatusNotFound, nil
} else if os.IsPermission(err) {
return http.StatusForbidden, nil
}
return http.StatusInternalServerError, err
}
defer file.Close()
input, err := ioutil.ReadAll(file)
if err != nil {
return http.StatusInternalServerError, err
}
L := lua.NewState()
defer L.Close()
ctx := interpreter.NewContext(L, w)
if err := interpreter.Interpret(L, input, &ctx.Out); err != nil {
var errReport error
ierr := err.(interpreter.InterpretationError)
if lerr, ok := ierr.Err.(*lua.ApiError); ok {
switch cause := lerr.Cause.(type) {
case *parse.Error:
errReport = fmt.Errorf("%s:%d (col %d): Syntax error near '%s'", fileName,
cause.Pos.Line+ierr.LineOffset, cause.Pos.Column, cause.Token)
case *lua.CompileError:
errReport = fmt.Errorf("%s:%d: %s", fileName,
cause.Line+ierr.LineOffset, cause.Message)
default:
errReport = fmt.Errorf("%s: %s", fileName, cause.Error())
}
}
return http.StatusInternalServerError, errReport
}
for _, f := range ctx.Callbacks {
err := f()
if err != nil {
// TODO
fmt.Println(err)
}
}
// Write the combined text to the http.ResponseWriter
w.Write(ctx.Out.Bytes())
return http.StatusOK, nil
}
return h.Next.ServeHTTP(w, r)
}