change directory behavior

This commit is contained in:
Sky Johnson 2025-05-01 13:18:24 -05:00
parent d50081ef55
commit 04450779f2
5 changed files with 36 additions and 78 deletions

View File

@ -99,7 +99,7 @@ func (s *Server) handleRequest(ctx *fasthttp.RequestCtx) {
} }
} }
// processRequest processes the actual request // In server.go, modify the processRequest method
func (s *Server) processRequest(ctx *fasthttp.RequestCtx) { func (s *Server) processRequest(ctx *fasthttp.RequestCtx) {
method := string(ctx.Method()) method := string(ctx.Method())
path := string(ctx.Path()) path := string(ctx.Path())
@ -130,9 +130,11 @@ func (s *Server) processRequest(ctx *fasthttp.RequestCtx) {
return return
} }
if _, found := s.staticRouter.Match(path); found { if s.staticRouter != nil {
s.staticRouter.ServeHTTP(ctx) if _, found := s.staticRouter.Match(path); found {
return s.staticRouter.ServeHTTP(ctx)
return
}
} }
ctx.SetContentType("text/html; charset=utf-8") ctx.SetContentType("text/html; charset=utf-8")

View File

@ -4,13 +4,13 @@ import (
"context" "context"
"errors" "errors"
"fmt" "fmt"
"os"
"time" "time"
"Moonshark/core/http" "Moonshark/core/http"
"Moonshark/core/routers" "Moonshark/core/routers"
"Moonshark/core/runner" "Moonshark/core/runner"
"Moonshark/core/sessions" "Moonshark/core/sessions"
"Moonshark/core/utils"
"Moonshark/core/utils/config" "Moonshark/core/utils/config"
"Moonshark/core/utils/logger" "Moonshark/core/utils/logger"
"Moonshark/core/watchers" "Moonshark/core/watchers"
@ -28,35 +28,37 @@ type Moonshark struct {
cleanupFuncs []func() error cleanupFuncs []func() error
} }
// dirExists checks if a directory exists without creating it
func dirExists(path string) bool {
info, err := os.Stat(path)
if err != nil {
return false
}
return info.IsDir()
}
// NewMoonshark creates a new Moonshark server instance // NewMoonshark creates a new Moonshark server instance
func NewMoonshark(configPath string) (*Moonshark, error) { func NewMoonshark(configPath string) (*Moonshark, error) {
// Initialize server struct
server := &Moonshark{} server := &Moonshark{}
// Load configuration
if err := server.loadConfig(configPath); err != nil { if err := server.loadConfig(configPath); err != nil {
return nil, err return nil, err
} }
// Configure logging
server.setupLogging() server.setupLogging()
// Initialize routers
if err := server.initRouters(); err != nil { if err := server.initRouters(); err != nil {
return nil, err return nil, err
} }
// Initialize Lua runner
if err := server.initRunner(); err != nil { if err := server.initRunner(); err != nil {
return nil, err return nil, err
} }
// Set up file watchers
if err := server.setupWatchers(); err != nil { if err := server.setupWatchers(); err != nil {
logger.Warning("Error setting up watchers: %v", err) logger.Warning("Error setting up watchers: %v", err)
} }
// Create HTTP server
server.HTTPServer = http.New( server.HTTPServer = http.New(
server.LuaRouter, server.LuaRouter,
server.StaticRouter, server.StaticRouter,
@ -74,7 +76,6 @@ func NewMoonshark(configPath string) (*Moonshark, error) {
func (s *Moonshark) loadConfig(configPath string) error { func (s *Moonshark) loadConfig(configPath string) error {
var err error var err error
// Load configuration from file
s.Config, err = config.Load(configPath) s.Config, err = config.Load(configPath)
if err != nil { if err != nil {
logger.Warning("Wipeout! Couldn't load config file: %v", err) logger.Warning("Wipeout! Couldn't load config file: %v", err)
@ -87,7 +88,6 @@ func (s *Moonshark) loadConfig(configPath string) error {
// setupLogging configures the logger based on config settings // setupLogging configures the logger based on config settings
func (s *Moonshark) setupLogging() { func (s *Moonshark) setupLogging() {
// Set log level from config
switch s.Config.Server.LogLevel { switch s.Config.Server.LogLevel {
case "warn": case "warn":
logger.SetLevel(logger.LevelWarning) logger.SetLevel(logger.LevelWarning)
@ -101,7 +101,6 @@ func (s *Moonshark) setupLogging() {
logger.SetLevel(logger.LevelInfo) logger.SetLevel(logger.LevelInfo)
} }
// Set debug mode if configured
if s.Config.Server.Debug { if s.Config.Server.Debug {
logger.EnableDebug() // Force debug logs regardless of level logger.EnableDebug() // Force debug logs regardless of level
logger.Debug("Debug mode is ready to party, bro") logger.Debug("Debug mode is ready to party, bro")
@ -110,13 +109,9 @@ func (s *Moonshark) setupLogging() {
// initRouters initializes the Lua and static routers // initRouters initializes the Lua and static routers
func (s *Moonshark) initRouters() error { func (s *Moonshark) initRouters() error {
// Ensure directories exist if !dirExists(s.Config.Dirs.Routes) {
if err := utils.EnsureDir(s.Config.Dirs.Routes); err != nil { logger.Fatal("Routes directory doesn't exist: %s", s.Config.Dirs.Routes)
return fmt.Errorf("routes directory doesn't exist and could not be created: %v", err) return fmt.Errorf("routes directory doesn't exist: %s", s.Config.Dirs.Routes)
}
if err := utils.EnsureDir(s.Config.Dirs.Static); err != nil {
return fmt.Errorf("static directory doesn't exist and could not be created: %v", err)
} }
// Initialize Lua router for dynamic routes // Initialize Lua router for dynamic routes
@ -141,36 +136,34 @@ func (s *Moonshark) initRouters() error {
} }
logger.Info("Lua router is stoked and riding routes from %s", s.Config.Dirs.Routes) logger.Info("Lua router is stoked and riding routes from %s", s.Config.Dirs.Routes)
// Initialize static file router if dirExists(s.Config.Dirs.Static) {
s.StaticRouter, err = routers.NewStaticRouter(s.Config.Dirs.Static) s.StaticRouter, err = routers.NewStaticRouter(s.Config.Dirs.Static)
if err != nil { if err != nil {
return fmt.Errorf("failed to initialize static router: %v", err) return fmt.Errorf("failed to initialize static router: %v", err)
}
logger.Info("Static router catching waves with files from %s", s.Config.Dirs.Static)
s.StaticRouter.EnableDebugLog()
} else {
logger.Warning("Static directory doesn't exist: %s - static file serving disabled", s.Config.Dirs.Static)
} }
logger.Info("Static router catching waves with files from %s", s.Config.Dirs.Static)
s.StaticRouter.EnableDebugLog()
return nil return nil
} }
// initRunner initializes the Lua runner // initRunner initializes the Lua runner
func (s *Moonshark) initRunner() error { func (s *Moonshark) initRunner() error {
// Ensure override directory exists if !dirExists(s.Config.Dirs.Override) {
if err := utils.EnsureDir(s.Config.Dirs.Override); err != nil { logger.Warning("Override directory doesn't exist: %s", s.Config.Dirs.Override)
logger.Warning("Override directory doesn't exist and could not be created: %v", err) s.Config.Dirs.Override = ""
s.Config.Dirs.Override = "" // Disable overrides if directory can't be created
} }
// Ensure lib directories exist
for _, dir := range s.Config.Dirs.Libs { for _, dir := range s.Config.Dirs.Libs {
if err := utils.EnsureDir(dir); err != nil { if !dirExists(dir) {
logger.Warning("Lib directory doesn't exist and could not be created: %v", err) logger.Warning("Lib directory doesn't exist: %s", dir)
} }
} }
// Initialize session manager
sessionManager := sessions.GlobalSessionManager sessionManager := sessions.GlobalSessionManager
// Configure session cookies
sessionManager.SetCookieOptions( sessionManager.SetCookieOptions(
"MoonsharkSID", // name "MoonsharkSID", // name
"/", // path "/", // path
@ -180,13 +173,11 @@ func (s *Moonshark) initRunner() error {
86400, // maxAge (1 day) 86400, // maxAge (1 day)
) )
// Set up runner options
runnerOpts := []runner.RunnerOption{ runnerOpts := []runner.RunnerOption{
runner.WithPoolSize(s.Config.Runner.PoolSize), runner.WithPoolSize(s.Config.Runner.PoolSize),
runner.WithLibDirs(s.Config.Dirs.Libs...), runner.WithLibDirs(s.Config.Dirs.Libs...),
} }
// Initialize the runner
var err error var err error
s.LuaRunner, err = runner.NewRunner(runnerOpts...) s.LuaRunner, err = runner.NewRunner(runnerOpts...)
if err != nil { if err != nil {

View File

@ -35,7 +35,6 @@ func NewStaticRouter(rootDir string) (*StaticRouter, error) {
return nil, errors.New("root path is not a directory") return nil, errors.New("root path is not a directory")
} }
// Create the FS handler with optimized settings
fs := &fasthttp.FS{ fs := &fasthttp.FS{
Root: rootDir, Root: rootDir,
IndexNames: []string{"index.html"}, IndexNames: []string{"index.html"},
@ -50,14 +49,13 @@ func NewStaticRouter(rootDir string) (*StaticRouter, error) {
r := &StaticRouter{ r := &StaticRouter{
fs: fs, fs: fs,
urlPrefix: "/static", // Default prefix urlPrefix: "/",
rootDir: rootDir, rootDir: rootDir,
log: false, log: false,
useBrotli: true, useBrotli: true,
useZstd: true, useZstd: true,
} }
// Set up the path rewrite based on the prefix
r.updatePathRewrite() r.updatePathRewrite()
return r, nil return r, nil
@ -78,7 +76,6 @@ func (r *StaticRouter) SetCompression(useGzip, useBrotli, useZstd bool) {
r.useBrotli = useBrotli r.useBrotli = useBrotli
r.useZstd = useZstd r.useZstd = useZstd
// Update handler to reflect changes
r.fsHandler = r.fs.NewRequestHandler() r.fsHandler = r.fs.NewRequestHandler()
} }
@ -117,7 +114,6 @@ func (r *StaticRouter) DisableDebugLog() {
func (r *StaticRouter) ServeHTTP(ctx *fasthttp.RequestCtx) { func (r *StaticRouter) ServeHTTP(ctx *fasthttp.RequestCtx) {
path := string(ctx.Path()) path := string(ctx.Path())
// Check if path starts with the prefix
if !strings.HasPrefix(path, r.urlPrefix) { if !strings.HasPrefix(path, r.urlPrefix) {
ctx.NotFound() ctx.NotFound()
return return
@ -127,21 +123,17 @@ func (r *StaticRouter) ServeHTTP(ctx *fasthttp.RequestCtx) {
logger.Debug("[StaticRouter] Serving: %s", path) logger.Debug("[StaticRouter] Serving: %s", path)
} }
// Handle the request with the FS handler
r.fsHandler(ctx) r.fsHandler(ctx)
} }
// Match finds a file path for the given URL path // Match finds a file path for the given URL path
func (r *StaticRouter) Match(urlPath string) (string, bool) { func (r *StaticRouter) Match(urlPath string) (string, bool) {
// Check if path starts with the prefix
if !strings.HasPrefix(urlPath, r.urlPrefix) { if !strings.HasPrefix(urlPath, r.urlPrefix) {
return "", false return "", false
} }
// Strip prefix
urlPath = strings.TrimPrefix(urlPath, r.urlPrefix) urlPath = strings.TrimPrefix(urlPath, r.urlPrefix)
// Make sure path starts with /
if !strings.HasPrefix(urlPath, "/") { if !strings.HasPrefix(urlPath, "/") {
urlPath = "/" + urlPath urlPath = "/" + urlPath
} }

View File

@ -51,7 +51,7 @@ func (s *Sandbox) AddModule(name string, module any) {
// Setup initializes the sandbox in a Lua state // Setup initializes the sandbox in a Lua state
func (s *Sandbox) Setup(state *luajit.State, verbose bool) error { func (s *Sandbox) Setup(state *luajit.State, verbose bool) error {
if verbose { if verbose {
logger.Server("Setting up sandbox...") logger.Debug("Setting up sandbox...")
} }
if err := loadSandboxIntoState(state, verbose); err != nil { if err := loadSandboxIntoState(state, verbose); err != nil {
@ -77,7 +77,7 @@ func (s *Sandbox) Setup(state *luajit.State, verbose bool) error {
s.mu.RUnlock() s.mu.RUnlock()
if verbose { if verbose {
logger.Server("Sandbox setup complete") logger.Debug("Sandbox setup complete")
} }
return nil return nil
} }

View File

@ -1,27 +0,0 @@
package utils
import (
"os"
"path/filepath"
)
// EnsureDir checks if a directory exists and creates it if it doesn't.
// Returns any error encountered during directory creation.
func EnsureDir(path string) error {
path = filepath.Clean(path)
info, err := os.Stat(path)
if err == nil {
if info.IsDir() {
return nil
}
return os.ErrExist
}
if !os.IsNotExist(err) {
return err
}
return os.MkdirAll(path, 0755)
}