286 lines
6.7 KiB
Go
286 lines
6.7 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"io/fs"
|
|
"net/http"
|
|
"os"
|
|
"path/filepath"
|
|
"regexp"
|
|
"strings"
|
|
|
|
"github.com/gomarkdown/markdown"
|
|
"github.com/gomarkdown/markdown/html"
|
|
"github.com/gomarkdown/markdown/parser"
|
|
"github.com/pelletier/go-toml/v2"
|
|
lua "github.com/yuin/gopher-lua"
|
|
|
|
"fes/src/config"
|
|
)
|
|
|
|
func handleDir(entries []os.DirEntry, wwwDir string, routes map[string]string, base string) error {
|
|
for _, entry := range entries {
|
|
if entry.IsDir() {
|
|
sub := filepath.Join(wwwDir, entry.Name())
|
|
subs, err := os.ReadDir(sub)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read %s: %w", sub, err)
|
|
}
|
|
next := base + "/" + entry.Name()
|
|
if err := handleDir(subs, sub, routes, next); err != nil {
|
|
return err
|
|
}
|
|
continue
|
|
}
|
|
if strings.HasSuffix(entry.Name(), ".lua") {
|
|
name := strings.TrimSuffix(entry.Name(), ".lua")
|
|
path := filepath.Join(wwwDir, entry.Name())
|
|
if name == "index" {
|
|
if base == "" {
|
|
routes["/"] = path
|
|
routes["/index"] = path
|
|
} else {
|
|
routes[base] = path
|
|
routes[base+"/index"] = path
|
|
}
|
|
} else {
|
|
if base == "" {
|
|
routes["/"+name] = path
|
|
} else {
|
|
routes[base+"/"+name] = path
|
|
}
|
|
}
|
|
}
|
|
}
|
|
return nil
|
|
}
|
|
|
|
func fixMalformedToml(content string) string {
|
|
re := regexp.MustCompile(`(?m)^(\s*\w+\s*=\s*)$`)
|
|
return re.ReplaceAllStringFunc(content, func(match string) string {
|
|
parts := strings.Split(strings.TrimSpace(match), "=")
|
|
if len(parts) == 2 && strings.TrimSpace(parts[1]) == "" {
|
|
key := strings.TrimSpace(parts[0])
|
|
return key + " = \"\""
|
|
}
|
|
return match
|
|
})
|
|
}
|
|
|
|
func markdownToHTML(mdText string) string {
|
|
extensions := parser.CommonExtensions | parser.AutoHeadingIDs | parser.NoEmptyLineBeforeBlock
|
|
p := parser.NewWithExtensions(extensions)
|
|
doc := p.Parse([]byte(mdText))
|
|
htmlFlags := html.CommonFlags | html.HrefTargetBlank
|
|
opts := html.RendererOptions{Flags: htmlFlags}
|
|
renderer := html.NewRenderer(opts)
|
|
return string(markdown.Render(doc, renderer))
|
|
}
|
|
|
|
func loadIncludeModules(L *lua.LState, includeDir string) *lua.LTable {
|
|
app := L.NewTable()
|
|
ents, err := os.ReadDir(includeDir)
|
|
if err != nil {
|
|
return app
|
|
}
|
|
for _, e := range ents {
|
|
if e.IsDir() {
|
|
continue
|
|
}
|
|
name := e.Name()
|
|
if !strings.HasSuffix(name, ".lua") {
|
|
continue
|
|
}
|
|
base := strings.TrimSuffix(name, ".lua")
|
|
path := filepath.Join(includeDir, name)
|
|
if err := L.DoFile(path); err != nil {
|
|
fmt.Printf("Failed to load %s: %v\n", path, err)
|
|
continue
|
|
}
|
|
val := L.Get(-1)
|
|
L.Pop(1)
|
|
tbl, ok := val.(*lua.LTable)
|
|
if !ok {
|
|
tbl = L.NewTable()
|
|
}
|
|
app.RawSetString(base, tbl)
|
|
}
|
|
return app
|
|
}
|
|
|
|
func loadLua(luaDir string, entry string, cfg *config.MyConfig) (string, error) {
|
|
L := lua.NewState()
|
|
defer L.Close()
|
|
|
|
rdents, err := fs.ReadDir(config.Core, "core")
|
|
if err == nil {
|
|
for _, de := range rdents {
|
|
if de.IsDir() {
|
|
continue
|
|
}
|
|
name := de.Name()
|
|
if !strings.HasSuffix(name, ".lua") {
|
|
continue
|
|
}
|
|
path := filepath.Join("core", name)
|
|
data, err := config.Core.ReadFile(path)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if err := L.DoString(string(data)); err != nil {
|
|
continue
|
|
}
|
|
}
|
|
}
|
|
|
|
L.PreloadModule("core.std", func(L *lua.LState) int {
|
|
data, err := config.Core.ReadFile("core/std.lua")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if err := L.DoString(string(data)); err != nil {
|
|
panic(err)
|
|
}
|
|
L.Push(L.Get(-1))
|
|
return 1
|
|
})
|
|
|
|
L.PreloadModule("core.symbol", func(L *lua.LState) int {
|
|
data, err := config.Core.ReadFile("core/symbol.lua")
|
|
if err != nil {
|
|
panic(err)
|
|
}
|
|
if err := L.DoString(string(data)); err != nil {
|
|
panic(err)
|
|
}
|
|
L.Push(L.Get(-1))
|
|
return 1
|
|
})
|
|
|
|
L.PreloadModule("fes", func(L *lua.LState) int {
|
|
mod := L.NewTable()
|
|
coreModules := []string{}
|
|
if ents, err := fs.ReadDir(config.Core, "core"); err == nil {
|
|
for _, e := range ents {
|
|
if e.IsDir() {
|
|
continue
|
|
}
|
|
n := e.Name()
|
|
if strings.HasSuffix(n, ".lua") {
|
|
coreModules = append(coreModules, strings.TrimSuffix(n, ".lua"))
|
|
}
|
|
}
|
|
}
|
|
for _, modName := range coreModules {
|
|
path := filepath.Join("core", modName+".lua")
|
|
data, err := config.Core.ReadFile(path)
|
|
if err != nil {
|
|
continue
|
|
}
|
|
if err := L.DoString(string(data)); err != nil {
|
|
continue
|
|
}
|
|
val := L.Get(-1)
|
|
L.Pop(1)
|
|
tbl, ok := val.(*lua.LTable)
|
|
if !ok || tbl == nil {
|
|
tbl = L.NewTable()
|
|
}
|
|
if modName == "builtin" {
|
|
tbl.ForEach(func(k, v lua.LValue) {
|
|
mod.RawSet(k, v)
|
|
})
|
|
} else {
|
|
mod.RawSetString(modName, tbl)
|
|
}
|
|
}
|
|
|
|
includeDir := filepath.Join(luaDir, "include")
|
|
appTbl := loadIncludeModules(L, includeDir)
|
|
mod.RawSetString("app", appTbl)
|
|
|
|
if cfg != nil {
|
|
siteTable := L.NewTable()
|
|
siteTable.RawSetString("version", lua.LString(cfg.App.Version))
|
|
siteTable.RawSetString("name", lua.LString(cfg.App.Name))
|
|
authorsTable := L.NewTable()
|
|
for i, author := range cfg.App.Authors {
|
|
authorsTable.RawSetInt(i+1, lua.LString(author))
|
|
}
|
|
siteTable.RawSetString("authors", authorsTable)
|
|
mod.RawSetString("site", siteTable)
|
|
}
|
|
|
|
mod.RawSetString("markdown_to_html", L.NewFunction(func(L *lua.LState) int {
|
|
mdText := L.ToString(1)
|
|
html := markdownToHTML(mdText)
|
|
L.Push(lua.LString(html))
|
|
return 1
|
|
}))
|
|
|
|
L.Push(mod)
|
|
return 1
|
|
})
|
|
|
|
if err := L.DoFile(entry); err != nil {
|
|
return "", err
|
|
}
|
|
|
|
top := L.GetTop()
|
|
if top == 0 {
|
|
return "", nil
|
|
}
|
|
resultVal := L.Get(-1)
|
|
L.SetGlobal("__fes_result", resultVal)
|
|
if err := L.DoString("return tostring(__fes_result)"); err != nil {
|
|
L.GetGlobal("__fes_result")
|
|
if s := L.ToString(-1); s != "" {
|
|
return s, nil
|
|
}
|
|
return "", nil
|
|
}
|
|
if s := L.ToString(-1); s != "" {
|
|
return s, nil
|
|
}
|
|
return "", nil
|
|
}
|
|
|
|
func Start(dir string) error {
|
|
tomlDocument, err := os.ReadFile(filepath.Join(dir, "Fes.toml"))
|
|
if err != nil {
|
|
return err
|
|
}
|
|
docStr := fixMalformedToml(string(tomlDocument))
|
|
var cfg config.MyConfig
|
|
err = toml.Unmarshal([]byte(docStr), &cfg)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to parse Fes.toml: %w", err)
|
|
}
|
|
|
|
wwwDir := filepath.Join(dir, "www")
|
|
entries, err := os.ReadDir(wwwDir)
|
|
if err != nil {
|
|
return fmt.Errorf("failed to read www directory: %w", err)
|
|
}
|
|
|
|
routes := make(map[string]string)
|
|
handleDir(entries, wwwDir, routes, "")
|
|
|
|
for route, luaPath := range routes {
|
|
func(rt string, lp string) {
|
|
http.HandleFunc(rt, func(w http.ResponseWriter, r *http.Request) {
|
|
fmt.Printf("-> %s\n", lp)
|
|
data, err := loadLua(dir, lp, &cfg)
|
|
if err != nil {
|
|
http.Error(w, fmt.Sprintf("Error loading page: %v", err), http.StatusInternalServerError)
|
|
return
|
|
}
|
|
w.Write([]byte(data))
|
|
})
|
|
}(route, luaPath)
|
|
}
|
|
|
|
fmt.Printf("Server is running on http://localhost:%d\n", *config.Port)
|
|
return http.ListenAndServe(fmt.Sprintf(":%d", *config.Port), nil)
|
|
}
|