-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathpubengine.go
More file actions
217 lines (188 loc) · 6.62 KB
/
pubengine.go
File metadata and controls
217 lines (188 loc) · 6.62 KB
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
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
// Package pubengine is a blog publishing engine built with Go, Echo, and templ.
// It provides blog CRUD, admin dashboard, analytics, RSS, and sitemap out of the box.
//
// Users provide their own templ templates via the ViewFuncs struct,
// and pubengine handles all the handler logic, middleware, and database operations.
package pubengine
import (
"fmt"
"io/fs"
"log"
"net/http"
"os"
"time"
"github.com/a-h/templ"
"github.com/labstack/echo/v4"
"github.com/eringen/pubengine/analytics"
)
// ViewFuncs holds user-provided templ components that the framework calls
// when rendering pages. This is the inversion-of-control mechanism that
// lets users own and customize all templates.
type ViewFuncs struct {
Home func(posts []BlogPost, activeTag string, tags []string, siteURL string) templ.Component
HomePartial func(posts []BlogPost, activeTag string, tags []string, siteURL string) templ.Component
BlogSection func(posts []BlogPost, activeTag string, tags []string) templ.Component
Post func(post BlogPost, posts []BlogPost, siteURL string) templ.Component
PostPartial func(post BlogPost, posts []BlogPost, siteURL string) templ.Component
AdminLogin func(errorMsg string, csrfToken string, googleLoginURL string) templ.Component
AdminDashboard func(posts []BlogPost, message string, csrfToken string) templ.Component
AdminFormPartial func(post BlogPost, csrfToken string) templ.Component
AdminImages func(images []Image, csrfToken string) templ.Component
NotFound func() templ.Component
ServerError func() templ.Component
}
// App is the central pubengine application. It wires together the store,
// cache, handlers, middleware, and user-provided templates.
type App struct {
Config SiteConfig
Echo *echo.Echo
Store *Store
Cache *PostCache
Views ViewFuncs
loginLimiter *LoginLimiter
analyticsStore *analytics.Store
customRoutes []func(*App)
staticDir string
}
// New creates a new pubengine App with the given configuration and view functions.
func New(cfg SiteConfig, views ViewFuncs, opts ...Option) *App {
cfg.setDefaults()
a := &App{
Config: cfg,
Echo: echo.New(),
Views: views,
staticDir: "public",
}
for _, opt := range opts {
opt(a)
}
return a
}
// Start initializes the database, cache, middleware, routes, and starts the server.
func (a *App) Start() error {
// Validate required config
if a.Config.AdminPassword == "" {
return fmt.Errorf("pubengine: AdminPassword is required")
}
if a.Config.SessionSecret == "" {
return fmt.Errorf("pubengine: SessionSecret is required")
}
// Initialize store
store, err := NewStore(a.Config.DatabasePath)
if err != nil {
return fmt.Errorf("pubengine: init store: %w", err)
}
a.Store = store
// Initialize cache
a.Cache = NewPostCache(a.Store, a.Config.PostCacheTTL)
// Initialize login limiter
a.loginLimiter = NewLoginLimiter(5, time.Minute)
// Initialize analytics if enabled
if a.Config.AnalyticsEnabled {
analyticsStore, err := analytics.NewStore(a.Config.AnalyticsDatabasePath)
if err != nil {
return fmt.Errorf("pubengine: init analytics: %w", err)
}
a.analyticsStore = analyticsStore
if err := analytics.InitSalt(analyticsStore); err != nil {
return fmt.Errorf("pubengine: init analytics salt: %w", err)
}
stopCleanup := analyticsStore.StartCleanupScheduler(365, 24*time.Hour)
defer stopCleanup()
}
// Setup middleware
a.setupMiddleware()
// Setup routes
a.setupRoutes()
// Apply custom routes
for _, fn := range a.customRoutes {
fn(a)
}
// Start server
if err := a.Echo.Start(a.Config.Addr); err != nil && err != http.ErrServerClosed {
return err
}
return nil
}
func (a *App) setupRoutes() {
e := a.Echo
// Serve embedded framework assets (talkdom.js, analytics.js, dashboard.min.js)
// These are served under /public/ and fall through to the user's static dir.
embeddedFS, _ := fs.Sub(EmbeddedAssets, "embedded")
embeddedHandler := http.FileServer(http.FS(embeddedFS))
e.GET("/public/talkdom.js", echo.WrapHandler(http.StripPrefix("/public/", embeddedHandler)))
e.GET("/public/analytics.js", echo.WrapHandler(http.StripPrefix("/public/", embeddedHandler)))
e.GET("/public/dashboard.min.js", echo.WrapHandler(http.StripPrefix("/public/", embeddedHandler)))
e.GET("/public/admin.css", echo.WrapHandler(http.StripPrefix("/public/", embeddedHandler)))
// User's static assets
e.Static("/public", a.staticDir)
e.GET("/favicon.svg", a.handleFavicon)
e.GET("/robots.txt", a.handleRobots)
// Public routes
e.GET("/sitemap.xml", a.handleSitemap)
e.GET("/feed.xml", a.handleFeed)
e.GET("/blog", handleBlogRedirect)
e.GET("/", a.handleHome)
e.GET("/blog/:slug/", a.handlePost)
// Admin routes
e.GET("/admin/", a.handleAdmin)
e.POST("/admin/login/", a.handleAdminLogin)
e.POST("/admin/logout/", handleAdminLogout)
e.GET("/admin/post/:slug/", a.handleAdminPost)
e.POST("/admin/save/", a.handleAdminSave)
e.DELETE("/admin/post/:slug/", a.handleAdminDelete)
e.GET("/admin/images/", a.handleImageList)
e.POST("/admin/images/upload/", a.handleImageUpload)
e.DELETE("/admin/images/:filename/", a.handleImageDelete)
// Google OAuth routes
if a.Config.GoogleAuthEnabled() {
e.GET("/admin/auth/google/", a.handleGoogleLogin)
e.GET("/admin/auth/google/callback", a.handleGoogleCallback)
}
// Analytics routes
if a.Config.AnalyticsEnabled && a.analyticsStore != nil {
analyticsHandler := analytics.NewHandler(a.analyticsStore)
analyticsAuthMiddleware := func(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
if !IsAdmin(c) {
return c.Redirect(http.StatusSeeOther, "/admin/")
}
return next(c)
}
}
publicGroup := e.Group("")
analyticsHandler.RegisterRoutes(e, publicGroup, analyticsAuthMiddleware)
e.GET("/admin/analytics/", func(c echo.Context) error {
if !IsAdmin(c) {
return c.Redirect(http.StatusSeeOther, "/admin/")
}
return analyticsHandler.DashboardHTML(c)
})
}
}
// Close cleans up resources. Call this when the app is shutting down.
func (a *App) Close() error {
if a.Store != nil {
a.Store.Close()
}
if a.analyticsStore != nil {
a.analyticsStore.Close()
}
return nil
}
// EnvOr returns the value of the environment variable key, or fallback if empty.
// This is a convenience function for use in scaffolded main.go files.
func EnvOr(key, fallback string) string {
if v := os.Getenv(key); v != "" {
return v
}
return fallback
}
// MustEnv returns the value of the environment variable key, or fatally exits if empty.
func MustEnv(key string) string {
v := os.Getenv(key)
if v == "" {
log.Fatalf("pubengine: required environment variable %s is not set", key)
}
return v
}