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
|
package server
import (
"encoding/json"
"fmt"
"html/template"
"net/http"
"os"
"path/filepath"
"strings"
"iblog/internal/builder"
"iblog/internal/db"
"github.com/gin-gonic/gin"
)
type PostHandler struct {
DB *db.DB
Templates *template.Template
PublicDir string
}
func NewPostHandler(database *db.DB, tmpl *template.Template, publicDir string) *PostHandler {
return &PostHandler{
DB: database,
Templates: tmpl,
PublicDir: publicDir,
}
}
// Serve dispatches to ServeHTML or ServeJSON based on the slug extension.
func (h *PostHandler) Serve(c *gin.Context) {
slug := c.Param("slug")
if strings.HasSuffix(slug, ".json") {
h.ServeJSON(c)
return
}
h.ServeHTML(c)
}
// ServeHTML serves the HTML version of a post.
func (h *PostHandler) ServeHTML(c *gin.Context) {
slug := c.Param("slug")
slug = strings.TrimSuffix(slug, ".html")
post, err := h.DB.GetPostBySlug(slug)
if err != nil {
if toSlug, rerr := h.DB.GetRedirect(slug); rerr == nil {
c.Redirect(http.StatusMovedPermanently, "/"+toSlug)
return
}
c.AbortWithStatus(http.StatusNotFound)
return
}
cacheFile := filepath.Join(h.PublicDir, slug+".html")
// Check cache freshness
if isCacheFresh(cacheFile, post.UpdatedAt) {
if f, err := os.Open(cacheFile); err == nil {
defer f.Close()
info, _ := os.Stat(cacheFile)
c.Header("Content-Type", "text/html; charset=utf-8")
http.ServeContent(c.Writer, c.Request, slug+".html", info.ModTime(), f)
return
}
}
// Render post
html, err := h.renderPostHTML(post)
if err != nil {
fmt.Fprintf(os.Stderr, "render post %s: %v\n", slug, err)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Atomic write: write to temp file, then rename
if err := os.MkdirAll(h.PublicDir, 0755); err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
tmpFile := cacheFile + ".tmp"
if err := os.WriteFile(tmpFile, []byte(html), 0644); err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if err := os.Rename(tmpFile, cacheFile); err != nil {
os.Remove(tmpFile)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Serve rendered HTML
c.Data(http.StatusOK, "text/html; charset=utf-8", []byte(html))
}
// ServeJSON handles GET /posts/:slug.json and serves the JSON version of a post.
func (h *PostHandler) ServeJSON(c *gin.Context) {
slug := c.Param("slug")
slug = strings.TrimSuffix(slug, ".json")
post, err := h.DB.GetPostBySlug(slug)
if err != nil {
if toSlug, rerr := h.DB.GetRedirect(slug); rerr == nil {
c.Redirect(http.StatusMovedPermanently, "/"+toSlug+".json")
return
}
c.AbortWithStatus(http.StatusNotFound)
return
}
cacheFile := filepath.Join(h.PublicDir, slug+".json")
// Check cache freshness
if isCacheFresh(cacheFile, post.UpdatedAt) {
if f, err := os.Open(cacheFile); err == nil {
defer f.Close()
info, _ := os.Stat(cacheFile)
c.Header("Content-Type", "application/json")
http.ServeContent(c.Writer, c.Request, slug+".json", info.ModTime(), f)
return
}
}
// Generate JSON representation
jsonData := map[string]interface{}{
"slug": post.Slug,
"title": post.Title,
"date": post.Date,
"tags": post.Tags,
"blocks": json.RawMessage(post.Blocks),
}
jsonBytes, _ := json.MarshalIndent(jsonData, "", " ")
// Atomic write
if err := os.MkdirAll(h.PublicDir, 0755); err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
tmpFile := cacheFile + ".tmp"
if err := os.WriteFile(tmpFile, jsonBytes, 0644); err != nil {
c.AbortWithStatus(http.StatusInternalServerError)
return
}
if err := os.Rename(tmpFile, cacheFile); err != nil {
os.Remove(tmpFile)
c.AbortWithStatus(http.StatusInternalServerError)
return
}
// Serve JSON
c.Header("Content-Type", "application/json")
c.Data(http.StatusOK, "application/json", jsonBytes)
}
// renderPostHTML renders a post to HTML using the base template.
func (h *PostHandler) renderPostHTML(post *db.PostRecord) (string, error) {
htmlBody, scripts, err := builder.RenderEditorJS(post.Blocks)
if err != nil {
return "", fmt.Errorf("render editorjs: %w", err)
}
pageData := builder.PageData{
Title: post.Title,
Content: template.HTML(htmlBody),
ComponentScripts: scripts,
Date: post.Date,
Tags: post.Tags,
Path: "/" + post.Slug,
}
var buf strings.Builder
if err := h.Templates.ExecuteTemplate(&buf, "post.html", pageData); err != nil {
return "", fmt.Errorf("template: %w", err)
}
return buf.String(), nil
}
// isCacheFresh checks if the cache file is newer than the post's updated_at timestamp.
func isCacheFresh(cacheFile string, updatedAtMicros int64) bool {
info, err := os.Stat(cacheFile)
if err != nil {
return false
}
cacheModTime := info.ModTime().UnixMicro()
return cacheModTime >= updatedAtMicros
}
|