-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
308 lines (280 loc) · 7.54 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
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
//go:generate go run -tags build build.go
package main
import (
"context"
"errors"
"fmt"
"io"
"io/fs"
"net"
"net/http"
"os"
"path/filepath"
"strconv"
"strings"
"text/template"
"time"
"embed"
"github.com/Darkness4/blog/db"
"github.com/Darkness4/blog/gen/index"
"github.com/Darkness4/blog/utils/color"
"github.com/Darkness4/blog/utils/math"
"github.com/Masterminds/sprig/v3"
"github.com/go-chi/chi/v5"
"github.com/joho/godotenv"
"github.com/rs/zerolog"
"github.com/rs/zerolog/hlog"
"github.com/rs/zerolog/log"
"github.com/urfave/cli/v2"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/jackc/pgx/v5/stdlib"
)
var (
//go:embed gen components base.html base.htmx 404.tmpl
html embed.FS
//go:embed static
static embed.FS
version = "dev"
listenAddress string
publicURL string
dbDSN string
)
var funcsMap = func() template.FuncMap {
f := sprig.TxtFuncMap()
f["computeColorByWord"] = color.ComputeByWord
return f
}
func ReadUserIP(r *http.Request) string {
IPAddress, _, _ := strings.Cut(r.Header.Get("X-Real-IP"), ",")
if IPAddress == "" {
IPAddress, _, _ = strings.Cut(r.Header.Get("X-Forwarded-For"), ",")
}
if IPAddress == "" {
IPAddress = r.RemoteAddr
}
addr := strings.ToLower(IPAddress)
host, _, err := net.SplitHostPort(addr)
if err != nil {
return addr
}
return host
}
var app = &cli.App{
Name: "blog",
Version: version,
Usage: "A blog in HTMX.",
Suggest: true,
Flags: []cli.Flag{
&cli.StringFlag{
Name: "listen.address",
Usage: "The address to listen on",
Value: ":3000",
Destination: &listenAddress,
EnvVars: []string{"LISTEN_ADDRESS"},
},
&cli.StringFlag{
Name: "public.url",
Usage: "The public URL",
Value: "https://blog.mnguyen.fr",
Destination: &publicURL,
EnvVars: []string{"PUBLIC_URL"},
},
&cli.StringFlag{
Name: "db.dsn",
Usage: "The DSN for the database",
Destination: &dbDSN,
EnvVars: []string{"DB_DSN"},
Required: true,
},
},
Action: func(cCtx *cli.Context) error {
ctx := cCtx.Context
log.Level(zerolog.DebugLevel)
// DB connection
pool, err := pgxpool.New(ctx, dbDSN)
if err != nil {
return err
}
defer pool.Close()
// Initial migration
sqldb := stdlib.OpenDBFromPool(pool)
if err := db.InitialMigration(sqldb); err != nil {
return err
}
// Set up DB queries
q := db.New(pool)
// Router
r := chi.NewRouter()
r.Use(hlog.NewHandler(log.Logger))
// Pages rendering
var renderFn http.HandlerFunc = func(w http.ResponseWriter, r *http.Request) {
cleanPath := filepath.Clean(r.URL.Path)
// Check if asset
fpath := filepath.Join("gen/pages", cleanPath)
if f, err := html.Open(fpath); err == nil {
isPage := func() bool {
defer f.Close()
finfo, err := f.Stat()
if err != nil {
log.Err(err).Msg("failed to fetch fileinfo")
http.Error(w, err.Error(), http.StatusInternalServerError)
return false
}
if finfo.IsDir() {
// It's a page, or a file not found
return true
}
// Serve the file
if _, err = io.Copy(w, f); err != nil {
log.Err(err).Msg("failed to serve file")
http.Error(w, err.Error(), http.StatusInternalServerError)
}
return false
}()
if !isPage {
return
}
} else if err != nil && !errors.Is(err, fs.ErrNotExist) {
log.Err(err).Msg("failed to read file")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
// It's a page
templatePath := filepath.Clean(fmt.Sprintf("gen/pages/%s/page.tmpl", cleanPath))
// Check if SSR
var base string
if r.Header.Get("Hx-Boosted") != "true" {
// Initial Rendering
base = "base.html"
} else {
// SSR
base = "base.htmx"
}
// Set up the template
t, err := template.New("base").
Funcs(funcsMap()).
ParseFS(html, base, templatePath, "components/*")
var is404 bool
if err != nil {
if strings.Contains(err.Error(), "no files") {
// Render 404
w.WriteHeader(http.StatusNotFound)
t, err = template.New("base").
Funcs(funcsMap()).
ParseFS(html, base, "404.tmpl", "components/*")
if err != nil {
panic(fmt.Sprintf("failed to parse 404.tmpl: %v", err))
}
is404 = true
} else {
log.Err(err).Msg("template error")
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
}
pageS := r.URL.Query().Get("page")
page, _ := strconv.Atoi(pageS)
var pv db.PageView
if !is404 {
rctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
pv, err = q.FindPageViewsOrZero(rctx, strings.ToLower(cleanPath))
if err != nil {
log.Err(err).Msg("failed to fetch page views")
}
}
if err := t.ExecuteTemplate(w, "base", struct {
Pager struct {
First int
Prev int
Current int
Next int
Last int
}
Index []index.Index
Path string
PublicURL string
PageViewsF string
PageViews int
}{
PublicURL: publicURL,
Path: r.URL.Path,
Pager: struct {
First int
Prev int
Current int
Next int
Last int
}{
First: 0,
Prev: math.MaxI(0, page-1),
Current: page,
Next: math.MinI(index.PageSize-1, page+1),
Last: index.PageSize - 1,
},
Index: index.Pages[page],
PageViewsF: math.FormatNumber(float64(pv.Views + 1)),
PageViews: int(pv.Views + 1),
}); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
return
}
if !is404 && cleanPath != "/" {
go func() {
rctx, cancel := context.WithTimeout(ctx, 5*time.Second)
defer cancel()
if err := q.CreateOrIncrementPageViewsOnUniqueIP(rctx, pool, strings.ToLower(cleanPath), ReadUserIP(r)); err != nil {
log.Err(err).Msg("failed to increment page views")
}
}()
}
}
r.Get("/rss", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/rss+xml")
if err := index.Feed.WriteRss(w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Get("/atom", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/atom+xml")
if err := index.Feed.WriteAtom(w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Get("/json", func(w http.ResponseWriter, _ *http.Request) {
w.Header().Set("Content-Type", "application/json")
if err := index.Feed.WriteJSON(w); err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
})
r.Get("/sitemap.xml", func(w http.ResponseWriter, _ *http.Request) {
b, err := index.ToSiteMap(index.Pages)
if err != nil {
http.Error(w, err.Error(), http.StatusInternalServerError)
}
w.Header().Set("Content-Type", "application/xml")
header := `<?xml version="1.0" encoding="UTF-8"?>`
fmt.Fprintf(w, "%s\n%s", header, b)
})
r.Get("/robots.txt", func(w http.ResponseWriter, _ *http.Request) {
fmt.Fprintf(w, `User-agent: *
Disallow:
Sitemap: %s/sitemap.xml
Sitemap: %s/rss
Sitemap: %s/atom
`, publicURL, publicURL, publicURL)
})
r.Get("/*", renderFn)
r.Handle("/static/*", http.FileServer(http.FS(static)))
log.Info().Str("listenAddress", listenAddress).Msg("listening")
return http.ListenAndServe(listenAddress, r)
},
}
func main() {
_ = godotenv.Load(".env.local")
_ = godotenv.Load(".env")
log.Logger = log.Logger.With().Caller().Logger()
if err := app.Run(os.Args); err != nil {
log.Fatal().Err(err).Msg("app crashed")
}
}