74 lines
1.7 KiB
Go
74 lines
1.7 KiB
Go
package server
|
|
|
|
import (
|
|
"fmt"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
|
|
"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()
|
|
|
|
// Hello world endpoint
|
|
r.Get("/", func(ctx router.Ctx, params []string) {
|
|
tmpl, err := templateCache.Load("hello.html")
|
|
if err != nil {
|
|
ctx.SetStatusCode(fasthttp.StatusInternalServerError)
|
|
fmt.Fprintf(ctx, "Template error: %v", err)
|
|
return
|
|
}
|
|
|
|
data := map[string]any{
|
|
"title": "Dragon Knight",
|
|
"message": "Hello World!",
|
|
}
|
|
|
|
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: true,
|
|
}
|
|
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)
|
|
} |