83 lines
1.9 KiB
Go

package server
import (
"fmt"
"log"
"os"
"path/filepath"
"dk/internal/middleware"
"dk/internal/router"
"dk/internal/template"
"github.com/valyala/fasthttp"
)
func Start(port string) error {
// Initialize template cache - use current working directory for development
cwd, err := os.Getwd()
if err != nil {
return fmt.Errorf("failed to get current working directory: %w", err)
}
templateCache := template.NewCache(cwd)
// Initialize router
r := router.New()
// Add timing middleware
r.Use(middleware.Timing())
// Hello world endpoint
r.Get("/", func(ctx router.Ctx, params []string) {
tmpl, err := templateCache.Load("layout.html")
if err != nil {
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
fmt.Fprintf(ctx, "Template error: %v", err)
return
}
data := map[string]any{
"title": "Dragon Knight",
"content": "Hello World!",
"totaltime": middleware.GetRequestTime(ctx),
"numqueries": "0", // Placeholder for now
"version": "1.0.0",
"build": "dev",
}
tmpl.WriteTo(ctx, data)
})
// Use current working directory for static files
assetsDir := filepath.Join(cwd, "assets")
// Static file server for /assets
fs := &fasthttp.FS{
Root: assetsDir,
Compress: false,
}
assetsHandler := fs.NewRequestHandler()
// Combined handler
requestHandler := func(ctx *fasthttp.RequestCtx) {
path := string(ctx.Path())
// Handle static assets - strip /assets prefix
if len(path) >= 7 && path[:7] == "/assets" {
// Strip the /assets prefix for the file system handler
originalPath := ctx.Path()
ctx.Request.URI().SetPath(path[7:]) // Remove "/assets" prefix
assetsHandler(ctx)
ctx.Request.URI().SetPathBytes(originalPath) // Restore original path
return
}
// Handle routes
r.ServeHTTP(ctx)
}
addr := ":" + port
log.Printf("Server starting on %s", addr)
return fasthttp.ListenAndServe(addr, requestHandler)
}