-
Notifications
You must be signed in to change notification settings - Fork 3
/
main.go
87 lines (76 loc) · 1.76 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
package main
import (
"bytes"
"context"
"embed"
"flag"
"fmt"
"io/fs"
"log"
"net/http"
"os"
"os/signal"
"time"
"github.com/yuin/goldmark"
"marwan.io/muxw"
"marwan.io/serverctx"
)
//go:embed public
var public embed.FS
var dev = flag.Bool("dev", false, "run in developer mode")
func main() {
flag.Parse()
r := muxw.NewRouter()
var public fs.FS = public
if *dev {
public = os.DirFS("public")
} else {
var err error
public, err = fs.Sub(public, "public")
if err != nil {
log.Fatal(err)
}
}
r.Get("/", serveFile(public, "index.html"))
r.Get("/talks", serveFile(public, "talks.html"))
r.Get("/blog", serveFile(public, "blogs.html"))
r.Get("/favicon.ico", serveFile(public, "favicon.ico"))
r.Get("/blog/{post}", serveBlogPost(public))
r.Mount("/public", http.StripPrefix("/public", http.FileServerFS(public)))
r.SetNotFoundHandler(notFoundVanity)
ctx, cancel := signal.NotifyContext(context.Background(), os.Interrupt)
defer cancel()
err := serverctx.Run(ctx, &http.Server{
Addr: ":3091",
Handler: r,
}, 5*time.Second)
if err != nil {
log.Fatal(err)
}
}
func serveFile(public fs.FS, file string) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
http.ServeFileFS(w, r, public, file)
}
}
func serveBlogPost(public fs.FS) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
file, err := fs.ReadFile(public, "blog/"+r.PathValue("post")+".md")
if err != nil {
http.NotFound(w, r)
return
}
var buf bytes.Buffer
err = goldmark.Convert(file, &buf)
if err != nil {
fmt.Println(err)
}
post, err := fs.ReadFile(public, "blogpost.html")
if err != nil {
http.Error(w, err.Error(), 500)
return
}
resp := fmt.Sprintf(string(post), buf.String())
fmt.Fprintln(w, resp)
}
}