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
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
|
# Gin Migration Implementation Plan
> **For agentic workers:** REQUIRED SUB-SKILL: Use superpowers:subagent-driven-development (recommended) or superpowers:executing-plans to implement this plan task-by-task. Steps use checkbox (`- [ ]`) syntax for tracking.
**Goal:** Migrate the nebbet admin server from `net/http` to Gin with RESTful routes and middleware-based auth.
**Architecture:** Replace the manual `ServeHTTP` handler with Gin's declarative routing. The `Server` struct gains a `*gin.Engine` field. Auth becomes reusable middleware. Route handlers update their signatures to use `*gin.Context`. Routes move under `/admin` namespace with RESTful patterns (GET/POST for forms, DELETE for removal).
**Tech Stack:** Go, Gin, existing auth/template system (unchanged)
---
## File Structure
**Files to modify:**
- `go.mod` — Add Gin dependency
- `internal/admin/server.go` — Core changes: NewServer(), middleware, handler rewrites
- `cmd/nebbet/main.go` — Update cmdServe() to use NewServer()
---
### Task 1: Add Gin Dependency
**Files:**
- Modify: `go.mod`
- [ ] **Step 1: Add Gin to go.mod**
Run:
```bash
cd /Users/ivarlovlie/p/nebbet.no && go get github.com/gin-gonic/gin
```
Expected output: Gin module downloaded and added to go.mod
- [ ] **Step 2: Verify go.mod was updated**
Run:
```bash
grep "github.com/gin-gonic/gin" go.mod
```
Expected output: A line like `github.com/gin-gonic/gin v1.X.X` (version may vary)
- [ ] **Step 3: Run go mod tidy**
Run:
```bash
go mod tidy
```
Expected: No errors, go.sum updated
---
### Task 2: Refactor server.go — Add NewServer() Constructor
**Files:**
- Modify: `internal/admin/server.go` (top section with Server struct)
- [ ] **Step 1: Update Server struct to include Gin engine**
Replace the struct definition:
```go
// Server is an HTTP handler for the admin post-management UI.
type Server struct {
// PostsDir is the directory where post markdown files are stored,
// e.g. "content/posts". It is created on first use if it doesn't exist.
PostsDir string
// AuthFile is the path to the htpasswd-compatible passwords file.
// Authentication is skipped when AuthFile is empty or the file doesn't exist.
AuthFile string
// Builder is used to rebuild pages after create/edit/delete operations.
Builder *builder.Builder
engine *gin.Engine
tmpl *template.Template
}
```
- [ ] **Step 2: Add imports for Gin**
Add to the imports section at the top of server.go:
```go
import (
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"regexp"
"strings"
"time"
"github.com/gin-gonic/gin"
"nebbet.no/internal/admin/auth"
"nebbet.no/internal/builder"
)
```
- [ ] **Step 3: Add NewServer() constructor function**
Add this after the Server struct definition (before any methods):
```go
// NewServer creates a new admin server with Gin routing and auth middleware.
func NewServer(postsDir, authFile string, builder *builder.Builder) *Server {
s := &Server{
PostsDir: postsDir,
AuthFile: authFile,
Builder: builder,
}
// Initialize Gin engine
s.engine = gin.Default()
// Load templates
s.tmpl = mustParseTemplates()
// Apply auth middleware to all routes
s.engine.Use(s.authMiddleware())
// Register routes under /admin prefix
admin := s.engine.Group("/admin")
{
// List posts
admin.GET("/", s.handleList)
// Create form and create post
admin.GET("/new", s.handleNew)
admin.POST("/", s.handleNewPost)
// Edit form and update post
admin.GET("/:slug", s.handleEdit)
admin.POST("/:slug", s.handleEdit)
// Delete post
admin.DELETE("/:slug", s.handleDelete)
}
return s
}
// Engine returns the Gin engine for this server.
func (s *Server) Engine() *gin.Engine {
return s.engine
}
```
---
### Task 3: Refactor server.go — Add Auth Middleware
**Files:**
- Modify: `internal/admin/server.go` (replace checkAuth method)
- [ ] **Step 1: Replace checkAuth with middleware function**
Remove the old `checkAuth()` method and add this in its place:
```go
// authMiddleware returns a Gin middleware that validates Basic Auth credentials.
func (s *Server) authMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
// Skip auth if no auth file is configured
if s.AuthFile == "" {
c.Next()
return
}
// Skip auth if auth file doesn't exist
if _, err := os.Stat(s.AuthFile); os.IsNotExist(err) {
c.Next()
return
}
// Extract Basic Auth credentials
username, password, ok := c.Request.BasicAuth()
if !ok {
c.Header("WWW-Authenticate", `Basic realm="Admin"`)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
// Verify credentials
a := auth.New(s.AuthFile)
valid, err := a.Verify(username, password)
if err != nil || !valid {
c.Header("WWW-Authenticate", `Basic realm="Admin"`)
c.AbortWithStatusJSON(http.StatusUnauthorized, gin.H{"error": "Unauthorized"})
return
}
// Auth succeeded, continue
c.Next()
}
}
```
---
### Task 4: Refactor server.go — Remove ServeHTTP and Update Handlers
**Files:**
- Modify: `internal/admin/server.go` (remove ServeHTTP, update handler signatures)
- [ ] **Step 1: Remove the ServeHTTP method**
Delete the entire `func (s *Server) ServeHTTP(w http.ResponseWriter, r *http.Request)` method (lines 45-70 in original).
- [ ] **Step 2: Update handleList signature and implementation**
Replace:
```go
func (s *Server) handleList(w http.ResponseWriter, r *http.Request) {
posts, err := s.listPosts()
if err != nil {
http.Error(w, "Failed to list posts: "+err.Error(), http.StatusInternalServerError)
return
}
s.render(w, "base", map[string]any{
"Title": "Posts",
"ContentTemplate": "list-content",
"Posts": posts,
})
}
```
With:
```go
func (s *Server) handleList(c *gin.Context) {
posts, err := s.listPosts()
if err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": "Failed to list posts: " + err.Error(),
})
return
}
c.HTML(http.StatusOK, "base", gin.H{
"Title": "Posts",
"ContentTemplate": "list-content",
"Posts": posts,
})
}
```
- [ ] **Step 3: Update handleNew signature and implementation**
Replace:
```go
func (s *Server) handleNew(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost {
s.handleNewPost(w, r)
return
}
s.render(w, "base", map[string]any{
"Title": "New Post",
"ContentTemplate": "form-content",
"Action": "/admin/new",
"Post": Post{Date: time.Now().Format("2006-01-02")},
"IsNew": true,
})
}
```
With:
```go
func (s *Server) handleNew(c *gin.Context) {
c.HTML(http.StatusOK, "base", gin.H{
"Title": "New Post",
"ContentTemplate": "form-content",
"Action": "/admin/new",
"Post": Post{Date: time.Now().Format("2006-01-02")},
"IsNew": true,
})
}
```
- [ ] **Step 4: Update handleNewPost signature and implementation**
Replace:
```go
func (s *Server) handleNewPost(w http.ResponseWriter, r *http.Request) {
p := postFromForm(r)
if p.Title == "" {
s.renderError(w, "Title is required")
return
}
if p.Slug == "" {
p.Slug = slugify(p.Title)
}
mdPath := filepath.Join(s.PostsDir, p.Slug+".md")
if err := os.MkdirAll(s.PostsDir, 0755); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if _, err := os.Stat(mdPath); err == nil {
s.renderError(w, fmt.Sprintf("Post %q already exists", p.Slug))
return
}
if err := writePostFile(mdPath, p); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.rebuild(mdPath)
http.Redirect(w, r, "/admin/", http.StatusSeeOther)
}
```
With:
```go
func (s *Server) handleNewPost(c *gin.Context) {
p := postFromForm(c)
if p.Title == "" {
s.renderError(c, "Title is required")
return
}
if p.Slug == "" {
p.Slug = slugify(p.Title)
}
mdPath := filepath.Join(s.PostsDir, p.Slug+".md")
if err := os.MkdirAll(s.PostsDir, 0755); err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
if _, err := os.Stat(mdPath); err == nil {
s.renderError(c, fmt.Sprintf("Post %q already exists", p.Slug))
return
}
if err := writePostFile(mdPath, p); err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
s.rebuild(mdPath)
c.Redirect(http.StatusSeeOther, "/admin/")
}
```
- [ ] **Step 5: Update handleEdit signature and implementation**
Replace:
```go
func (s *Server) handleEdit(w http.ResponseWriter, r *http.Request, slug string) {
mdPath := filepath.Join(s.PostsDir, slug+".md")
p, err := readPostFile(mdPath, slug)
if err != nil {
http.NotFound(w, r)
return
}
if r.Method == http.MethodPost {
updated := postFromForm(r)
updated.Slug = slug // slug is immutable after creation
if updated.Title == "" {
s.renderError(w, "Title is required")
return
}
if err := writePostFile(mdPath, updated); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
s.rebuild(mdPath)
http.Redirect(w, r, "/admin/", http.StatusSeeOther)
return
}
s.render(w, "base", map[string]any{
"Title": "Edit Post",
"ContentTemplate": "form-content",
"Action": "/admin/" + slug + "/edit",
"Post": p,
"IsNew": false,
})
}
```
With:
```go
func (s *Server) handleEdit(c *gin.Context) {
slug := c.Param("slug")
mdPath := filepath.Join(s.PostsDir, slug+".md")
p, err := readPostFile(mdPath, slug)
if err != nil {
c.HTML(http.StatusNotFound, "base", gin.H{
"Title": "Not Found",
"ContentTemplate": "error-content",
"Message": "Post not found",
})
return
}
if c.Request.Method == http.MethodPost {
updated := postFromForm(c)
updated.Slug = slug // slug is immutable after creation
if updated.Title == "" {
s.renderError(c, "Title is required")
return
}
if err := writePostFile(mdPath, updated); err != nil {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
s.rebuild(mdPath)
c.Redirect(http.StatusSeeOther, "/admin/")
return
}
c.HTML(http.StatusOK, "base", gin.H{
"Title": "Edit Post",
"ContentTemplate": "form-content",
"Action": "/admin/" + slug,
"Post": p,
"IsNew": false,
})
}
```
- [ ] **Step 6: Update handleDelete signature and implementation**
Replace:
```go
func (s *Server) handleDelete(w http.ResponseWriter, r *http.Request, slug string) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
mdPath := filepath.Join(s.PostsDir, slug+".md")
if err := os.Remove(mdPath); err != nil && !os.IsNotExist(err) {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if s.Builder != nil {
_ = s.Builder.RemovePage(mdPath)
}
http.Redirect(w, r, "/admin/", http.StatusSeeOther)
}
```
With:
```go
func (s *Server) handleDelete(c *gin.Context) {
slug := c.Param("slug")
mdPath := filepath.Join(s.PostsDir, slug+".md")
if err := os.Remove(mdPath); err != nil && !os.IsNotExist(err) {
c.HTML(http.StatusInternalServerError, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": err.Error(),
})
return
}
if s.Builder != nil {
_ = s.Builder.RemovePage(mdPath)
}
c.Redirect(http.StatusSeeOther, "/admin/")
}
```
---
### Task 5: Refactor server.go — Update Helper Functions
**Files:**
- Modify: `internal/admin/server.go` (helper functions section)
- [ ] **Step 1: Update render() helper**
Replace:
```go
func (s *Server) render(w http.ResponseWriter, name string, data map[string]any) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if err := s.tmpl.ExecuteTemplate(w, name, data); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
}
```
With:
```go
func (s *Server) render(c *gin.Context, name string, data gin.H) {
if err := s.tmpl.ExecuteTemplate(c.Writer, name, data); err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
}
}
```
- [ ] **Step 2: Update renderError() helper**
Replace:
```go
func (s *Server) renderError(w http.ResponseWriter, msg string) {
w.Header().Set("Content-Type", "text/html; charset=utf-8")
w.WriteHeader(http.StatusBadRequest)
_ = s.tmpl.ExecuteTemplate(w, "base", map[string]any{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": msg,
})
}
```
With:
```go
func (s *Server) renderError(c *gin.Context, msg string) {
c.HTML(http.StatusBadRequest, "base", gin.H{
"Title": "Error",
"ContentTemplate": "error-content",
"Message": msg,
})
}
```
- [ ] **Step 3: Update postFromForm() to accept *gin.Context**
Replace:
```go
// postFromForm reads a post from an HTTP form submission.
func postFromForm(r *http.Request) Post {
_ = r.ParseForm()
return Post{
Title: strings.TrimSpace(r.FormValue("title")),
Date: strings.TrimSpace(r.FormValue("date")),
Tags: strings.TrimSpace(r.FormValue("tags")),
Content: r.FormValue("content"),
}
}
```
With:
```go
// postFromForm reads a post from an HTTP form submission.
func postFromForm(c *gin.Context) Post {
return Post{
Title: strings.TrimSpace(c.PostForm("title")),
Date: strings.TrimSpace(c.PostForm("date")),
Tags: strings.TrimSpace(c.PostForm("tags")),
Content: c.PostForm("content"),
}
}
```
---
### Task 6: Update cmd/nebbet/main.go
**Files:**
- Modify: `cmd/nebbet/main.go` (cmdServe function)
- [ ] **Step 1: Update import to include Gin**
Add `"github.com/gin-gonic/gin"` to the imports section:
```go
import (
"flag"
"fmt"
"net/http"
"os"
"github.com/gin-gonic/gin"
"nebbet.no/internal/admin"
"nebbet.no/internal/admin/auth"
"nebbet.no/internal/builder"
"nebbet.no/internal/db"
)
```
- [ ] **Step 2: Rewrite cmdServe() function**
Replace the entire `cmdServe()` function with:
```go
func cmdServe(args []string) {
fs := flag.NewFlagSet("serve", flag.ExitOnError)
port := fs.String("port", "8080", "port to listen on")
_ = fs.Parse(args)
b := mustBuilder()
defer b.MetaDB.Close()
defer b.SearchDB.Close()
// Initial build.
if err := b.BuildAll(); err != nil {
fmt.Fprintln(os.Stderr, "build error:", err)
os.Exit(1)
}
// Watch in background.
go func() {
if err := b.Watch(); err != nil {
fmt.Fprintln(os.Stderr, "watch error:", err)
}
}()
// Create admin server with Gin
adminSrv := admin.NewServer(postsDir, passwordFile, b)
engine := adminSrv.Engine()
// Serve dependencies (lib/)
engine.Static("/lib", "lib")
// Serve static site from public/
engine.Static("/", outputDir)
addr := ":" + *port
fmt.Printf("listening on http://localhost%s\n", addr)
fmt.Printf(" public site: http://localhost%s/\n", addr)
fmt.Printf(" admin UI: http://localhost%s/admin/\n", addr)
if err := engine.Run(addr); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
}
```
---
### Task 7: Test the Migration
**Files:**
- Test: Manual testing (no automated tests needed for this migration)
- [ ] **Step 1: Build the project**
Run:
```bash
cd /Users/ivarlovlie/p/nebbet.no && go build ./cmd/nebbet
```
Expected: Binary builds without errors
- [ ] **Step 2: Start the server**
Run:
```bash
go run ./cmd/nebbet serve --port 8080
```
Expected output:
```
listening on http://localhost:8080
public site: http://localhost:8080/
admin UI: http://localhost:8080/admin/
```
- [ ] **Step 3: Test list posts endpoint**
Open browser: `http://localhost:8080/admin/`
Expected: Posts list page loads (may show empty if no posts)
- [ ] **Step 4: Create a new post**
- Navigate to `http://localhost:8080/admin/new`
- Fill in: Title, Date, Tags, Content
- Click "Create" (or submit button)
Expected: Redirects to `/admin/`, new post appears in list
- [ ] **Step 5: Edit a post**
- Click edit button on a post in the list
- Modify a field (e.g., title)
- Submit
Expected: Redirects to `/admin/`, post shows updated content
- [ ] **Step 6: Delete a post**
- On the edit page, click delete button
- Confirm deletion
Expected: Redirects to `/admin/`, post no longer in list
- [ ] **Step 7: Test static file serving**
- Navigate to `http://localhost:8080/`
- Check that public site loads
- Navigate to `http://localhost:8080/lib/` to verify lib/ is served
Expected: Both static file paths work
- [ ] **Step 8: Test auth**
- Stop the server (Ctrl+C)
- In another terminal, create a user if needed:
```bash
go run ./cmd/nebbet user add testuser
# Enter a password when prompted
```
- Start the server again
- Visit `http://localhost:8080/admin/`
- When prompted for auth, enter invalid credentials
Expected: 401 Unauthorized error
- Enter valid credentials (testuser + password)
Expected: Admin page loads
---
## Self-Review Checklist
✓ **Spec coverage:**
- Route migration (Task 2 NewServer) ✓
- Auth middleware (Task 3) ✓
- Handler refactoring (Task 4) ✓
- Helper functions (Task 5) ✓
- CLI integration (Task 6) ✓
- Testing (Task 7) ✓
✓ **Placeholder scan:** No TBDs, all code is complete and specific
✓ **Type consistency:**
- Handler signatures consistently `(c *gin.Context)`
- Form helpers use `postFromForm(c)`
- Template rendering uses `c.HTML()`
- No mismatched method names
✓ **Function signatures match:** All handlers in NewServer() route definitions match their actual signatures
|