~tsileo/blobstash

ref: ae2f65aeb1544cf14ee4c620886c23eff1f00631 blobstash/pkg/extra/extra.go -rw-r--r-- 1.8 KiB View raw
ae2f65aeThomas Sileo deps: update deps a month ago
                                                                                
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
package extra // import "a4.io/blobstash/pkg/extra"

import (
	"fmt"
	"io/ioutil"
	"net/http"
	"path/filepath"
	"strings"

	"github.com/yuin/gopher-lua"
)

type Extra struct {
	resourceCache map[string]lua.LString
}

func setupExtra(e *Extra) func(*lua.LState) int {
	return func(L *lua.LState) int {
		// register functions to the table
		mod := L.SetFuncs(L.NewTable(), map[string]lua.LGFunction{
			"noop": func(L *lua.LState) int {
				return 0
			},
			"glob": func(L *lua.LState) int {
				// match(<glob pattern>, <name>)
				matched, err := filepath.Match(L.ToString(1), L.ToString(2))
				if err != nil {
					panic(err)
				}
				if matched {
					L.Push(lua.LTrue)
				} else {
					L.Push(lua.LFalse)
				}
				return 1
			},
			"replace": func(L *lua.LState) int {
				in := L.ToString(1)
				toreplace := L.ToString(2)
				replacement := L.ToString(3)
				L.Push(lua.LString(strings.Replace(in, toreplace, replacement, 1)))
				return 1
			},
			"split": func(L *lua.LState) int {
				tbl := L.NewTable()
				for _, part := range strings.Split(L.ToString(1), L.ToString(2)) {
					tbl.Append(lua.LString(part))
				}
				L.Push(tbl)
				return 1
			},
			"embed_http_resource": func(L *lua.LState) int {
				url := L.ToString(1)

				resp, err := http.Get(url)
				if err != nil {
					panic(fmt.Errorf("failed to fetch URL: %s: %s", url, err))
				}
				defer resp.Body.Close()

				body, err := ioutil.ReadAll(resp.Body)
				if err != nil {
					panic(fmt.Errorf("failed to read response: %s", err))
				}

				data := lua.LString(body)

				e.resourceCache[url] = data

				L.Push(data)
				return 1
			},
		})
		// returns the module
		L.Push(mod)
		return 1
	}
}

func Setup(L *lua.LState) *Extra {
	e := &Extra{
		resourceCache: map[string]lua.LString{},
	}
	// luautil.InterfaceToLValue(L, nil)
	L.PreloadModule("extra", setupExtra(e))
	return e
}