-
Notifications
You must be signed in to change notification settings - Fork 1
/
server.go
167 lines (144 loc) · 4.27 KB
/
server.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
package app
import (
"bytes"
"context"
"fmt"
"log"
"net/http"
"path"
"strings"
"time"
"github.com/vdimir/markify/util"
"github.com/vdimir/markify/view"
"github.com/pkg/errors"
"github.com/go-chi/chi"
)
const fixedPagesPrefixDir = "static_pages"
// StartServer listen incoming requests. Blocking function
func (app *App) StartServer(host string, port uint16) {
serverURL := host
if serverURL == "" {
serverURL = "localhost"
}
log.Printf("[INFO] starting server at http://%s:%d\n", serverURL, port)
app.Addr = fmt.Sprintf("%s:%d", host, port)
app.httpServer = &http.Server{
Addr: app.Addr,
Handler: app.Routes(),
}
err := app.httpServer.ListenAndServe()
if err != nil && err != http.ErrServerClosed {
log.Printf("[ERROR] server listening error: %s (http://%s:%d)\n", err, serverURL, port)
}
log.Printf("[INFO] server stopped")
}
// Shutdown stop server
func (app *App) Shutdown() {
log.Print("[WARN] shutdown server")
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
if app.httpServer != nil {
if err := app.httpServer.Shutdown(ctx); err != nil {
log.Printf("[WARN] http shutdown error, %s", err)
}
log.Print("[DEBUG] shutdown http server completed")
}
}
func (app *App) respondError(err error, req *CreatePasteRequest, w http.ResponseWriter) {
if errUser, ok := err.(UserError); ok {
returnToPageCtx := &view.EditorContext{
Title: fmt.Sprintf("%s :(", defaultTitle),
Msg: errUser.String(),
}
if req != nil {
returnToPageCtx.InitialText = req.Text
}
app.viewTemplate(http.StatusBadRequest, returnToPageCtx, w)
} else {
app.serverError(err, w)
}
}
func (app *App) serverError(err error, w http.ResponseWriter) {
log.Printf("[ERROR] %v", err)
ctx := &view.StatusContext{
Title: "Error",
HeaderMsg: "500",
Msg: "Internal Server error",
}
app.viewTemplate(http.StatusInternalServerError, ctx, w)
}
func (app *App) viewTemplate(code int, ctx view.TemplateContext, w http.ResponseWriter) {
htmlBuf := &bytes.Buffer{}
err := app.htmlView.RenderPage(htmlBuf, ctx)
if err != nil {
log.Printf("[ERROR] %v", errors.Wrapf(err, "cannot render template %s", ctx.FileName()))
app.serverErrorFallback(w)
return
}
if code > 0 {
w.WriteHeader(code)
}
_, err = htmlBuf.WriteTo(w)
if err != nil {
log.Printf("[ERROR] %v", err)
return
}
}
func (app *App) serverErrorFallback(w http.ResponseWriter) {
w.WriteHeader(http.StatusInternalServerError)
rawHTML := "<!DOCTYPE html>" +
"<html><head><title>Error</title></head><body>" +
"Internal Server Error" +
"</body></html>\n"
w.Write([]byte(rawHTML))
}
func (app *App) addFixedPages(r chi.Router) {
createDebugHanlder := func(filePath string, raw bool) func(w http.ResponseWriter, r *http.Request) {
handler := func(w http.ResponseWriter, r *http.Request) {
f, err := app.staticFs.Open(filePath)
if err != nil {
panic(err)
}
doc, err := app.converter.Convert(f, "markdown")
if err != nil {
panic(err)
}
app.viewDocument(&Document{*doc, "",time.Time{}}, "", r.URL.Path, w)
}
return handler
}
err := util.WalkFiles(app.staticFs, fixedPagesPrefixDir, func(data []byte, filePath string) error {
name := strings.TrimSuffix(filePath, ".md")
doc, err := app.converter.Convert(bytes.NewReader(data), "markdown")
if err != nil {
return err
}
handler := func(w http.ResponseWriter, r *http.Request) {
app.viewDocument(&Document{*doc, "",time.Time{}}, "", r.URL.Path, w)
}
if app.cfg.Debug {
handler = createDebugHanlder(path.Join(fixedPagesPrefixDir, filePath), false)
}
r.Get("/"+name, handler)
return nil
})
if err != nil {
panic(errors.Wrap(err, "cannot add fixed pages"))
}
}
// addFileServer sets up a http.FileServer handler to serve static files
func (app *App) addFileServer(r chi.Router, path string) {
if strings.ContainsAny(path, "{}*/") {
panic("FileServer path not permit URL parameters slashes.")
}
webFs := http.FileServer(http.FS(app.staticFs))
fileHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if strings.HasSuffix(r.URL.Path, "/") {
app.notFound(w, r)
return
}
webFs.ServeHTTP(w, r)
})
r.Method("GET", "/"+path+"/{fileName}", fileHandler)
r.Method("GET", "/favicon.ico", util.AddRoutePrefix("/public", webFs.ServeHTTP))
}