-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
140 lines (111 loc) · 3.42 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
package main
import (
"context"
"embed"
"fmt"
html "html/template"
"io/fs"
"net/http"
"os"
"os/signal"
"regexp"
"strings"
"syscall"
"time"
"github.com/gomarkdown/markdown"
nlogrus "github.com/meatballhat/negroni-logrus"
"github.com/phyber/negroni-gzip/gzip"
"github.com/sirupsen/logrus"
"github.com/unrolled/render"
nsecure "github.com/unrolled/secure"
"github.com/urfave/negroni"
)
var (
pathRx = regexp.MustCompile("^/posts/(?P<post>[-_a-zA-Z0-9]+)$")
dateRx = regexp.MustCompile("^(2[0-9]{3}-[0-1][1-9])-(.*)")
//go:embed posts/*
postsFS embed.FS
)
func main() {
renderer := render.New(render.Options{
Directory: "templates",
Layout: "layout",
})
mux := http.NewServeMux()
mux.HandleFunc("GET /health", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "healthy")
})
mux.HandleFunc("GET /robots.txt", func(w http.ResponseWriter, req *http.Request) {
fmt.Fprintf(w, "User-agent: *\nAllow: /\n")
})
mux.HandleFunc("GET /posts", func(w http.ResponseWriter, req *http.Request) {
files, err := fs.Glob(postsFS, "posts/*.md")
if err != nil {
_ = renderer.HTML(w, http.StatusInternalServerError, "500", nil)
return
}
datedPosts := [][]string{}
ongoingPosts := [][]string{}
for _, file := range files {
filename := strings.ReplaceAll(file, "posts/", "")
slug := strings.ReplaceAll(filename, ".md", "")
matches := dateRx.FindStringSubmatch(slug)
if len(matches) == 0 {
title := strings.ReplaceAll(slug, "-", " ")
ongoingPosts = append(ongoingPosts, []string{slug, title})
} else {
date := matches[1]
title := strings.ReplaceAll(matches[2], "-", " ")
datedPosts = append(datedPosts, []string{slug, title, date})
}
}
for i := 0; i < len(datedPosts)/2; i++ {
t := datedPosts[i]
datedPosts[i] = datedPosts[len(datedPosts)-i-1]
datedPosts[len(datedPosts)-i-1] = t
}
_ = renderer.HTML(w, http.StatusOK, "posts", map[string]interface{}{"ongoing": ongoingPosts, "dated": datedPosts})
})
mux.HandleFunc("GET /posts/", func(w http.ResponseWriter, req *http.Request) {
if !pathRx.MatchString(req.URL.Path) {
_ = renderer.HTML(w, http.StatusNotFound, "404", nil)
return
}
matches := pathRx.FindAllStringSubmatch(req.URL.Path, -1)
post := matches[0][1]
path := "posts/" + post + ".md"
contents, err := postsFS.ReadFile(path)
if err != nil {
_ = renderer.HTML(w, http.StatusNotFound, "404", nil)
return
}
rendered := html.HTML(markdown.ToHTML(contents, nil, nil))
_ = renderer.HTML(w, http.StatusOK, "post", rendered)
})
mux.HandleFunc("/", func(w http.ResponseWriter, req *http.Request) {
if req.URL.Path != "" && req.URL.Path != "/" {
_ = renderer.HTML(w, http.StatusNotFound, "404", nil)
return
}
_ = renderer.HTML(w, http.StatusOK, "index", nil)
})
level := logrus.InfoLevel
n := negroni.New()
n.Use(negroni.NewRecovery())
n.Use(nlogrus.NewCustomMiddleware(level, &logrus.JSONFormatter{}, "web"))
n.Use(gzip.Gzip(gzip.DefaultCompression))
n.Use(negroni.HandlerFunc(nsecure.New().HandlerFuncWithNext))
n.Use(negroni.NewStatic(http.Dir("public")))
n.UseHandler(mux)
ctx, cancel := signal.NotifyContext(context.Background(), syscall.SIGTERM)
defer cancel()
server := &http.Server{Addr: ":8080", Handler: n}
go func() {
_ = server.ListenAndServe()
}()
<-ctx.Done()
ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second)
defer cancel()
_ = server.Shutdown(ctx)
os.Exit(0)
}