-
Notifications
You must be signed in to change notification settings - Fork 1
/
main.go
189 lines (159 loc) · 4.84 KB
/
main.go
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
package main
import (
"fmt"
"lilmail/config"
"lilmail/handlers/api"
"lilmail/handlers/web"
"lilmail/storage"
"log"
"strings"
"time"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/logger"
"github.com/gofiber/fiber/v2/middleware/recover"
"github.com/gofiber/fiber/v2/middleware/session"
"github.com/gofiber/template/html/v2"
)
var store *session.Store
func init() {
// Create file storage
storage, err := storage.NewFileStorage("./sessions")
if err != nil {
log.Fatal("Failed to initialize session storage:", err)
}
store = session.New(session.Config{
Storage: storage,
Expiration: 24 * time.Hour,
CookieSecure: false, // Set to true in production with HTTPS
CookieHTTPOnly: true,
})
}
// Helper function to determine if request is an API request
func isAPIRequest(c *fiber.Ctx) bool {
if c == nil {
return false
}
// Check for HTMX request first
if c.Get("HX-Request") != "" {
return true
}
// Safely check if path starts with /api
path := c.Path()
return len(path) >= 4 && path[:4] == "/api"
}
func main() {
// Load configuration
config, err := config.LoadConfig("config.toml")
if err != nil {
log.Fatal("Failed to load config:", err)
}
// Initialize template engine with custom functions
engine := html.New("./templates", ".html")
// String manipulation functions
engine.AddFunc("split", strings.Split)
engine.AddFunc("join", strings.Join)
engine.AddFunc("lower", strings.ToLower)
engine.AddFunc("upper", strings.ToUpper)
engine.AddFunc("title", strings.Title)
engine.AddFunc("trim", strings.TrimSpace)
engine.AddFunc("hasPrefix", strings.HasPrefix)
// Date formatting function
engine.AddFunc("formatDate", func(t time.Time) string {
return t.Format("Jan 02, 2006 15:04")
})
// File size formatting function
engine.AddFunc("formatSize", func(size int64) string {
const unit = 1024
if size < unit {
return fmt.Sprintf("%d B", size)
}
div, exp := int64(unit), 0
for n := size / unit; n >= unit; n /= unit {
div *= unit
exp++
}
return fmt.Sprintf("%.1f %cB", float64(size)/float64(div), "KMGTPE"[exp])
})
engine.Reload(true)
// Initialize Fiber with template engine
app := fiber.New(fiber.Config{
Views: engine,
ViewsLayout: "layouts/main", // Default layout
ErrorHandler: func(c *fiber.Ctx, err error) error {
code := fiber.StatusInternalServerError
if e, ok := err.(*fiber.Error); ok {
code = e.Code
}
// Handle API requests differently
if isAPIRequest(c) {
return c.Status(code).JSON(fiber.Map{
"error": err.Error(),
})
}
// Render error page for regular requests
return c.Status(code).Render("error", fiber.Map{
"Error": err.Error(),
"Code": code,
})
},
})
// Add middleware
app.Use(recover.New()) // Recover from panics
app.Use(logger.New()) // Request logging
// Serve static files
app.Static("/assets", "./assets", fiber.Static{
Compress: true,
CacheDuration: 24 * time.Hour,
})
// Initialize web handlers
webAuthHandler := web.NewAuthHandler(store, config)
webEmailHandler := web.NewEmailHandler(store, config, webAuthHandler)
// Public routes
app.Get("/login", webAuthHandler.ShowLogin)
app.Post("/login", webAuthHandler.HandleLogin)
app.Get("/logout", webAuthHandler.HandleLogout)
// Protected routes group
protected := app.Group("", api.SessionMiddleware(store))
// Main web routes
protected.Get("/", webEmailHandler.HandleInbox) // Default to inbox
protected.Get("/inbox", webEmailHandler.HandleInbox) // Explicit inbox route
protected.Get("/folder/:name", webEmailHandler.HandleFolder)
// API routes - Keep these paths exactly as they were before
apiRoutes := protected.Group("/api")
{
// Email routes
apiRoutes.Get("/email/:id", webEmailHandler.HandleEmailView)
apiRoutes.Delete("/email/:id", webEmailHandler.HandleDeleteEmail)
// Folder routes - This is the important fix
apiRoutes.Get("/folder/:name/emails", webEmailHandler.HandleFolderEmails) // Match the path in HTML
// Composition routes
apiRoutes.Post("/compose", webEmailHandler.HandleComposeEmail)
}
// HTMX routes (partial template renders)
htmx := protected.Group("/htmx")
{
htmx.Get("/email/:id", webEmailHandler.HandleEmailView)
htmx.Get("/folder/:name/emails", webEmailHandler.HandleFolderEmails)
}
// Health check endpoint
app.Get("/health", func(c *fiber.Ctx) error {
return c.SendString("OK")
})
// 404 Handler for undefined routes
app.Use(func(c *fiber.Ctx) error {
if isAPIRequest(c) {
return c.Status(404).JSON(fiber.Map{
"error": "Not Found",
})
}
return c.Status(404).Render("error", fiber.Map{
"Error": "Page not found",
"Code": 404,
})
})
// Start server
log.Printf("Starting server on port %d...\n", config.Server.Port)
if err := app.Listen(fmt.Sprintf(":%d", config.Server.Port)); err != nil {
log.Fatal("Error starting server: ", err)
}
}