-
Notifications
You must be signed in to change notification settings - Fork 2
Expand file tree
/
Copy pathmain.go
More file actions
1157 lines (1045 loc) · 26.9 KB
/
Copy pathmain.go
File metadata and controls
1157 lines (1045 loc) · 26.9 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
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package main
import (
"bytes"
"context"
"encoding/json"
"errors"
"flag"
"fmt"
"io"
"net/http"
"os"
"path"
"path/filepath"
"sort"
"strings"
"sync"
"text/template"
"encoding/base64"
"github.com/c4pt0r/log"
"github.com/gomarkdown/markdown"
lua "github.com/yuin/gopher-lua"
)
var (
// rootDir is the root directory of the website.
rootDir = flag.String("rootDir", "./site", "root directory")
siteName = flag.String("sitename", "crew", "site name")
siteSubtitle = flag.String("site-subtitle", "Bringing more minimalism and sanity to the web, in a suckless way", "site name")
// customPageTpl is the path to a custom page template.
customPageTpl = flag.String("page-tpl", "", "custom page template file, use -print-page-tpl to print the default template")
printDefaultTpl = flag.Bool("print-default-page-template", false, "print the default page template")
basenameMode = flag.Bool("basename-mode", false, "run crew in basename mode, rendering URLs without .md suffix")
// _rootDir is the absolute path to the root directory
_rootDir string
// addr is the address to listen on.
addr = flag.String("addr", ":8080", "address to listen on")
)
var (
pageTpl = `<!DOCTYPE html>
<html>
<head>
<title>{{ .Title }}</title>
<link rel="shortcut icon" href="/_static/favicon.ico" type="image/vnd.microsoft.icon">
<link rel="stylesheet" href="/_static/highlight.js/default.min.css">
<script src="/_static/highlight.js/highlight.min.js"></script>
<script>hljs.initHighlightingOnLoad();</script>
<link rel="stylesheet" href="/_static/style.css" type="text/css" media="screen, handheld" title="default">
<link rel="shortcut icon" href="/_static/favicon.ico" type="image/vnd.microsoft.icon">
<meta charset="UTF-8">
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8">
</head>
<body>
<header>
<nav class="head-nav">
<div class="left">
<a href="http://quotes.cat-v.org">quotes</a> |
<a href="http://doc.cat-v.org">docs</a> |
<a href="http://repo.cat-v.org">repo</a> |
<a href="http://go-lang.cat-v.org">golang</a> |
<a href="http://sam.cat-v.org">sam</a> |
<a href="http://man.cat-v.org">man</a> |
<a href="http://acme.cat-v.org">acme</a> |
<a href="http://glenda.cat-v.org">Glenda</a> |
<a href="http://ninetimes.cat-v.org">9times</a> |
<a href="http://harmful.cat-v.org">harmful</a> |
<a href="http://9p.cat-v.org/">9P</a> |
<a href="http://cat-v.org">cat-v.org</a>
</div>
<div class="right">
<span class="doNotDisplay">Related sites:</span>
| <a href="/sitemap">site map</a>
</div>
</nav>
<h1><a href="/">{{ .Headline }} <span id="headerSubTitle">{{ .SubHeadline }}</span></a></h1>
</header>
<nav id="side-bar">
<div>
{{ .Nav }}
</div>
</nav>
<article>
{{ .Body }}
</article>
<footer>
<br class="doNotDisplay doNotPrint" />
<div style="margin-right: auto;"><a href="http://crew.0xffff.me">Powered by crew</a></div>
</footer>
</body></html>
`
)
var (
// for render navbar & sitemap
_rootNode *node
)
// state is the global state for lua scripts
type state struct {
m map[string]interface{}
sync.RWMutex
}
func (s *state) Get(key string) interface{} {
s.RLock()
defer s.RUnlock()
return s.m[key]
}
func (s *state) Set(key string, value interface{}) {
s.Lock()
defer s.Unlock()
s.m[key] = value
}
func (s *state) Delete(key string) {
s.Lock()
defer s.Unlock()
delete(s.m, key)
}
var (
_state = &state{
m: make(map[string]interface{}),
}
)
func getRootNode() *node {
return _rootNode
}
func init() {
flag.Parse()
var err error
_rootDir = *rootDir
_rootNode, err = newNodeFromPath(_rootDir)
if err != nil {
log.Fatal(err)
}
if *customPageTpl != "" {
// read template file and replace pageTpl
b, err := os.ReadFile(*customPageTpl)
if err != nil {
log.Fatal(err)
}
pageTpl = string(b)
}
}
type NodeType int
const (
// NodeTypeFile is a file node.
NodeTypeFile NodeType = iota
)
func (ntp NodeType) String() string {
switch ntp {
case NodeTypeFile:
return "file"
default:
return "unknown"
}
}
func NodeTypeFromStr(s string) NodeType {
switch s {
case "file":
return NodeTypeFile
default:
return NodeTypeFile
}
}
type node struct {
// filepath is the absolute path to the file
filepath string
// key is the key to the node in the database
key string
// rpcEndpoint is the endpoint to the rpc server
rpcEndpoint string
title string
desc string
isDir bool
isHidden bool
tp NodeType
authToken string
basicAuth struct {
username string
password string
}
}
type nodeConf struct {
Title string `json:"title'"`
Desc string `json:"desc"`
IsHidden bool `json:"hidden"`
// Type is the type of the node, it can be "file"
Tp string `json:"type"`
// Key is the key to the node in the database if the node type is "kv", default value is the node URL
Key string `json:"key"`
// RpcEndpoint is the endpoint of the JsonRPC server if the node type is "rpc", default value is the node URL
RpcEndpoint string `json:"rpc_endpoint"`
// AuthToken is the token to access the node in header
AuthToken string `json:"auth_token"`
BasicAuth struct {
Username string `json:"username"`
Password string `json:"password"`
} `json:"basic_auth"`
}
func (n *node) URL() string {
// get the relative path to the root directory
if n.filepath == _rootDir {
return "/"
}
// get the relative path
relPath, err := filepath.Rel(_rootDir, n.filepath)
if err != nil {
// this should never happen
log.Fatal(err)
}
// replace spaces with underscores
relPath = strings.Replace(relPath, " ", "_", -1)
// add the leading slash
relPath = "/" + relPath
// trim ".md" suffix from node URL if running in basename mode
if *basenameMode {
relPath = strings.TrimSuffix(relPath, ".md")
}
return relPath
}
func isReservedName(name string) bool {
if strings.HasPrefix(name, ".") ||
strings.HasPrefix(name, "_") ||
strings.HasSuffix(name, ".conf.json") ||
name == "index.html" ||
name == "index.md" {
return true
}
return false
}
func (n *node) getSubNodes() ([]*node, error) {
// get the files in the directory
if !n.isDir {
return nil, nil
}
files, err := os.ReadDir(n.filepath)
if err != nil {
return nil, err
}
// create the nodes
var ns []*node
for _, f := range files {
// skip hidden/meta files
if isReservedName(f.Name()) {
continue
}
node, err := newNodeFromPath(path.Join(n.filepath, f.Name()))
if err != nil {
return nil, err
}
ns = append(ns, node)
}
// sort the nodes
sortNodes(ns)
return ns, nil
}
func sortNodes(ns []*node) {
// sort the nodes, directories first, then files
sort.Slice(ns, func(i, j int) bool {
if ns[i].isDir && !ns[j].isDir {
return true
}
return ns[i].title < ns[j].title
})
}
func (n *node) getParentNode() (*node, error) {
// get the parent directory
if path.Clean(n.filepath) == path.Clean(_rootDir) {
return nil, nil
}
parentDir := path.Dir(n.filepath)
// create the node
return newNodeFromPath(parentDir)
}
func (n *node) ext() string {
return filepath.Ext(n.filepath)
}
func (n *node) Render(ctx context.Context) ([]byte, error) {
if n.isDir {
return n.renderDir(ctx)
}
switch n.ext() {
case ".md":
return n.renderMarkdown(ctx)
case ".html":
return n.renderHTML(ctx)
case ".lua":
return n.renderLua(ctx)
default:
return n.renderHTML(ctx)
}
}
func (n *node) renderMarkdown(ctx context.Context) ([]byte, error) {
filePath := n.filepath
content, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
// convert markdown to html
output := markdown.ToHTML(content, nil, nil)
return output, nil
}
func (n *node) renderHTML(ctx context.Context) ([]byte, error) {
return n.rawContent()
}
func (n *node) rawContent() ([]byte, error) {
// if it's directory, just return index file
if n.isDir {
n, err := getIndexNodeForDir(n.filepath)
if err != nil {
return nil, err
}
if n != nil {
return n.rawContent()
} else {
return nil, fmt.Errorf("no index file (index.html or index.md) found for directory")
}
}
filePath := n.filepath
content, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
return content, nil
}
func nodeTree(wr io.Writer, root *node, prefix string) {
subnodes, _ := root.getSubNodes()
if len(subnodes) > 0 {
wr.Write([]byte(prefix + "<ul>"))
}
for _, n := range subnodes {
if n.isHidden {
continue
}
if n.isDir {
wr.Write([]byte("<li><a href=\"" + n.URL() + "/\">" + n.title + "/</a> " + n.desc + "</li>"))
} else {
wr.Write([]byte("<li><a href=\"" + n.URL() + "\">" + n.title + "</a> " + n.desc + "</li>"))
}
nodeTree(wr, n, prefix)
}
if len(subnodes) > 0 {
wr.Write([]byte(prefix + "</ul>"))
}
}
func getIndexNodeForDir(dir string) (*node, error) {
htmlIndex := path.Join(dir, "index.html")
if fileExists(htmlIndex) {
return newNodeFromPath(htmlIndex)
}
mdIndex := path.Join(dir, "index.md")
if fileExists(mdIndex) {
return newNodeFromPath(mdIndex)
}
return nil, nil
}
func (n *node) renderDir(ctx context.Context) ([]byte, error) {
// if there's _index.md or _index.html, render that
if indexNode, err := getIndexNodeForDir(n.filepath); err == nil && indexNode != nil {
return indexNode.Render(ctx)
}
// get the sub nodes
subNodes, err := n.getSubNodes()
if err != nil {
return nil, err
}
var buf bytes.Buffer
buf.WriteString("<h1>" + n.URL() + "</h1>")
buf.WriteString("<ul>")
for _, n := range subNodes {
if n.isHidden {
continue
}
buf.WriteString("<li>")
if n.isDir {
buf.WriteString("<a href=\"" + n.URL() + "/\">" + n.title + "/</a> " + n.desc)
} else {
buf.WriteString("<a href=\"" + n.URL() + "\">" + n.title + "</a> " + n.desc)
}
buf.WriteString("</li>")
}
buf.WriteString("</ul>")
return buf.Bytes(), nil
}
func (n *node) String() string {
if n.isDir {
return fmt.Sprintf("%s [D]: %s", n.filepath, n.title)
}
return fmt.Sprintf("%s [F]: %s", n.filepath, n.title)
}
func fileExists(fpath string) bool {
_, err := os.Stat(fpath)
if os.IsNotExist(err) {
return false
} else if err != nil {
log.E(err)
return false
}
return true
}
func getConfigFileForFile(fpath string) (bool, string, error) {
cfgPath := ""
info, err := os.Stat(fpath)
if err != nil {
return false, "", err
}
if !info.IsDir() {
dir, fn := path.Split(fpath)
cfgPath = path.Join(dir, fn+".conf.json")
return false, cfgPath, nil
} else {
cfgPath = path.Join(fpath, ".conf.json")
return true, cfgPath, nil
}
}
func newNodeFromPath(fullname string) (*node, error) {
fpath := fullname
// check if is a directory
fname := filepath.Base(fpath)
title := strings.TrimSuffix(fname, filepath.Ext(fname))
// replace underscores with spaces
title = strings.Replace(title, "_", " ", -1)
// node desc
desc := ""
hidden := false
tp := "file"
key := ""
rpcEndpoint := ""
authToken := ""
basicAuth := struct {
username string
password string
}{}
isDir, cfgPath, err := getConfigFileForFile(fpath)
if err != nil {
return nil, err
}
if fileExists(cfgPath) {
data, err := os.ReadFile(cfgPath)
if err != nil {
return nil, err
}
var cfg nodeConf
err = json.Unmarshal(data, &cfg)
if err != nil {
return nil, err
}
if len(cfg.Title) > 0 {
title = cfg.Title
}
if len(cfg.Desc) > 0 {
desc = cfg.Desc
}
if cfg.IsHidden {
hidden = true
}
if len(cfg.Tp) > 0 {
tp = cfg.Tp
if cfg.Tp == NodeTypeFile.String() && cfg.RpcEndpoint != "" {
rpcEndpoint = cfg.RpcEndpoint
}
}
if len(cfg.AuthToken) > 0 {
authToken = cfg.AuthToken
}
if len(cfg.BasicAuth.Username) > 0 && len(cfg.BasicAuth.Password) > 0 {
basicAuth.username = cfg.BasicAuth.Username
basicAuth.password = cfg.BasicAuth.Password
}
}
return &node{
filepath: fpath,
title: title,
desc: desc,
isHidden: hidden,
isDir: isDir,
tp: NodeTypeFromStr(tp),
key: key,
rpcEndpoint: rpcEndpoint,
authToken: authToken,
basicAuth: basicAuth,
}, nil
}
// +-Title------------------+
// | Headerline SubHeadline |
// +------------------------+
// | | |
// | N | |
// | a | Body |
// | v | |
// | | |
// +------------------------|
// | Footer |
// +------------------------+
type page struct {
node *node
// for the template
Header string
Headline string
SubHeadline string
Footer string
Nav string
Body string
Title string
Vals map[string]string
bodyRender func(p *page, ctx context.Context) ([]byte, error)
}
func pageFromNode(n *node) *page {
p := &page{
node: n,
Headline: *siteName,
SubHeadline: *siteSubtitle,
}
p.Title = n.title
return p
}
func sitemapPage() *page {
p := pageFromNode(getRootNode())
p.bodyRender = func(p *page, ctx context.Context) ([]byte, error) {
var buf bytes.Buffer
buf.WriteString("<h1> Site map </h1>")
nodeTree(&buf, p.node, "")
return buf.Bytes(), nil
}
return p
}
func filterNode(ns []*node, f func(*node) bool) []*node {
var filtered []*node
for _, n := range ns {
if f(n) {
filtered = append(filtered, n)
}
}
return filtered
}
func i(text string) string {
return "<i>" + text + "</i>"
}
func b(text string) string {
return "<b>" + text + "</b>"
}
func printList(from *node, to *node) (string, error) {
var buf bytes.Buffer
buf.WriteString("<ul>")
subnodes, err := from.getSubNodes()
if err != nil {
return "", err
}
for _, n := range subnodes {
if n.isHidden {
continue
}
buf.WriteString("<li>")
title := n.title
if n.isDir {
if strings.HasPrefix(to.filepath, n.filepath) {
title = i(title)
if n.filepath == to.filepath {
title = b(title)
}
title = "» " + title
} else {
title = "› " + title
}
buf.WriteString("<a href=\"" + n.URL() + "\">" + title + "/</a>")
} else {
title = "› " + title
if n.filepath == to.filepath {
title = "» " + n.title
title = b(title)
}
buf.WriteString("<a href=\"" + n.URL() + "\">" + title + "</a>")
}
if n.isDir && strings.HasPrefix(to.filepath, n.filepath) {
buf.WriteString("<ul>")
out, err := printList(n, to)
if err != nil {
return "", err
}
buf.WriteString(out)
buf.WriteString("</ul>")
}
buf.WriteString("</li>")
}
buf.WriteString("</ul>")
return buf.String(), nil
}
func (p *page) renderNav() ([]byte, error) {
out, err := printList(getRootNode(), p.node)
if err != nil {
return nil, err
}
return []byte(out), nil
}
func (p *page) Render(ctx context.Context) ([]byte, error) {
// if raw flag is set, just return the raw data
if params, ok := ctx.Value("params").(map[string]string); ok {
if v, ok := params["raw"]; ok && (v == "true" || v == "1") {
return p.node.rawContent()
}
}
tpl, err := template.New("page").Parse(pageTpl)
if err != nil {
return nil, err
}
// get the body
var body []byte
if p.bodyRender == nil {
body, err = p.node.Render(ctx)
if err != nil {
return nil, err
}
} else {
body, err = p.bodyRender(p, ctx)
if err != nil {
return nil, err
}
}
p.Body = string(body)
// get nav
nav, err := p.renderNav()
if err != nil {
return nil, err
}
p.Nav = string(nav)
var buf bytes.Buffer
if err := tpl.Execute(&buf, p); err != nil {
return nil, err
}
return buf.Bytes(), nil
}
func serverStatic(w http.ResponseWriter, r *http.Request) {
// get the absolute path to the file
filepath := filepath.Join(_rootDir, r.URL.Path)
// check if the file exists
if fi, err := os.Stat(filepath); (err == nil && fi.IsDir()) || os.IsNotExist(err) {
http.NotFound(w, r)
return
}
// serve the file
http.ServeFile(w, r, filepath)
}
// get query params from http.Request
func getQueryParams(r *http.Request) map[string]string {
params := make(map[string]string)
for k, v := range r.URL.Query() {
params[k] = v[0]
}
return params
}
func httpServer(addr string) error {
http.HandleFunc("/", func(w http.ResponseWriter, r *http.Request) {
// get the path from the request, and remove the leading slash
var page *page
log.Infof("%s %s %s", r.RemoteAddr, r.Method, r.URL)
path := r.URL.Path[1:]
if strings.HasPrefix(path, "_static") {
serverStatic(w, r)
return
} else if strings.HasPrefix(path, "sitemap") {
// site map
page = sitemapPage()
} else {
// get the node for the path
fpath := filepath.Join(_rootDir, path)
// fallback to adding "*.md" suffix to file path if no file found
// this ensures correct functioning of basename mode, disabled by default
if _, err := os.Stat(fpath); errors.Is(err, os.ErrNotExist) {
fpath = filepath.Join(_rootDir, path+".md")
}
node, err := newNodeFromPath(fpath)
if err != nil {
if os.IsNotExist(err) {
http.NotFound(w, r)
return
} else {
log.E(err)
http.Error(w, "", http.StatusInternalServerError)
}
return
}
if err != nil {
log.E(err)
http.Error(w, "", http.StatusInternalServerError)
return
}
// render the node
if node.authToken != "" {
// check http header got the auth token
if v := r.Header.Get("Authorization"); len(v) > 0 {
// split the Bearer token
parts := strings.Split(v, " ")
if !(len(parts) == 2 && parts[0] == "Bearer" && parts[1] == node.authToken) {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
} else {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
}
// Check for basic auth
authNode := node
for authNode != nil {
if authNode.basicAuth.username != "" && authNode.basicAuth.password != "" {
auth := r.Header.Get("Authorization")
if !checkBasicAuth(auth, authNode.basicAuth.username, authNode.basicAuth.password) {
w.Header().Set("WWW-Authenticate", `Basic realm="Restricted"`)
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
break
}
authNode, _ = authNode.getParentNode()
}
// For .lua files with POST/PUT/DELETE methods, handle directly
if node.ext() == ".lua" && (r.Method == "POST" || r.Method == "PUT" || r.Method == "DELETE") {
ctx := context.WithValue(
context.Background(),
"request",
r,
)
content, err := node.Render(ctx)
if err != nil {
log.E(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(content)
return
}
page = pageFromNode(node)
}
// Add request to context
ctx := context.WithValue(
context.Background(),
"request",
r,
)
content, err := page.Render(ctx)
if err != nil {
log.E(err)
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
w.Write(content)
})
log.I("Starting server on", addr)
return http.ListenAndServe(addr, nil)
}
func checkBasicAuth(auth, username, password string) bool {
if !strings.HasPrefix(auth, "Basic ") {
return false
}
payload, _ := base64.StdEncoding.DecodeString(auth[6:])
pair := strings.SplitN(string(payload), ":", 2)
if len(pair) != 2 {
return false
}
return pair[0] == username && pair[1] == password
}
func (n *node) renderLua(ctx context.Context) ([]byte, error) {
L := lua.NewState()
defer L.Close()
// Create crew table
crewTable := L.NewTable()
// Create state table
stateTable := L.NewTable()
// Add get method
L.SetField(stateTable, "get", L.NewFunction(func(L *lua.LState) int {
key := L.CheckString(1)
value := _state.Get(key)
if value == nil {
L.Push(lua.LNil)
return 1
}
// Convert Go value to Lua value
switch v := value.(type) {
case string:
L.Push(lua.LString(v))
case int:
L.Push(lua.LNumber(v))
case float64:
L.Push(lua.LNumber(v))
case bool:
L.Push(lua.LBool(v))
default:
L.Push(lua.LNil)
}
return 1
}))
// Add set method
L.SetField(stateTable, "set", L.NewFunction(func(L *lua.LState) int {
key := L.CheckString(1)
value := L.Get(2)
// Convert Lua value to Go value
var goValue interface{}
switch value.Type() {
case lua.LTString:
goValue = string(value.(lua.LString))
case lua.LTNumber:
goValue = float64(value.(lua.LNumber))
case lua.LTBool:
goValue = bool(value.(lua.LBool))
default:
L.Push(lua.LBool(false))
return 1
}
_state.Set(key, goValue)
L.Push(lua.LBool(true))
return 1
}))
// Add delete method
L.SetField(stateTable, "delete", L.NewFunction(func(L *lua.LState) int {
key := L.CheckString(1)
_state.Delete(key)
return 0
}))
// Add state table to crew
L.SetField(crewTable, "state", stateTable)
// Add node functions to crew
L.SetField(crewTable, "createNode", L.NewFunction(func(L *lua.LState) int {
nodePath := L.CheckString(1)
content := L.CheckString(2)
absPath := filepath.Join(_rootDir, nodePath)
if err := os.MkdirAll(filepath.Dir(absPath), 0755); err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(err.Error()))
return 2
}
if err := os.WriteFile(absPath, []byte(content), 0644); err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(lua.LBool(true))
return 1
}))
L.SetField(crewTable, "readNode", L.NewFunction(func(L *lua.LState) int {
nodePath := L.CheckString(1)
absPath := filepath.Join(_rootDir, nodePath)
content, err := os.ReadFile(absPath)
if err != nil {
L.Push(lua.LNil)
L.Push(lua.LString(err.Error()))
return 2
}
L.Push(lua.LString(string(content)))
return 1
}))
L.SetField(crewTable, "removeNode", L.NewFunction(func(L *lua.LState) int {
nodePath := L.CheckString(1)
absPath := filepath.Join(_rootDir, nodePath)
fileInfo, err := os.Stat(absPath)
if err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(err.Error()))
return 2
}
if fileInfo.IsDir() {
// Read directory contents
entries, err := os.ReadDir(absPath)
if err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(err.Error()))
return 2
}
// Check if directory is empty (ignoring hidden files and config files)
hasVisibleFiles := false
for _, entry := range entries {
if !isReservedName(entry.Name()) {
hasVisibleFiles = true
break
}
}
if hasVisibleFiles {
L.Push(lua.LBool(false))
L.Push(lua.LString("cannot remove non-empty directory"))
return 2
}
// Remove the empty directory and its config file
configPath := filepath.Join(absPath, ".conf.json")
if _, err := os.Stat(configPath); err == nil {
if err := os.Remove(configPath); err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(fmt.Sprintf("failed to remove config file: %v", err)))
return 2
}
}
if err := os.Remove(absPath); err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(fmt.Sprintf("failed to remove directory: %v", err)))
return 2
}
} else {
// Remove the file and its config file
if err := os.Remove(absPath); err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(err.Error()))
return 2
}
// Try to remove the config file if it exists
configPath := absPath + ".conf.json"
if _, err := os.Stat(configPath); err == nil {
if err := os.Remove(configPath); err != nil {
L.Push(lua.LBool(false))
L.Push(lua.LString(fmt.Sprintf("file removed but failed to remove config file: %v", err)))
return 2
}
}
}
L.Push(lua.LBool(true))
return 1
}))