-
Notifications
You must be signed in to change notification settings - Fork 0
/
helpers.go
110 lines (90 loc) · 2.55 KB
/
helpers.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
package main
import (
"bytes"
"fmt"
"net/http"
"os"
"runtime/debug"
"strconv"
"strings"
"sync"
"time"
"github.com/tomasen/realip"
)
type defaultKvTableCache struct {
cache *kvTable
once sync.Once
}
var defaultKvTableCaches = map[string]*defaultKvTableCache{
"Env": {},
"General": {},
}
func (app *application) serverError(w http.ResponseWriter, err error) {
trace := fmt.Sprintf("%s\n%s", err.Error(), debug.Stack())
app.errorLog.Output(2, trace)
app.clientError(w, http.StatusInternalServerError)
}
func (app *application) clientError(w http.ResponseWriter, status int) {
http.Error(w, http.StatusText(status), status)
}
func (app *application) notFound(w http.ResponseWriter) {
app.clientError(w, http.StatusNotFound)
}
func (app *application) render(w http.ResponseWriter, r *http.Request, name string, td *templateData) {
ts, ok := app.templateCache[name]
if !ok {
app.serverError(w, fmt.Errorf("the template %s does not exist", name))
}
buf := new(bytes.Buffer)
err := ts.Execute(buf, app.addDefaultData(td, r))
if err != nil {
app.serverError(w, err)
return
}
buf.WriteTo(w)
}
func (app *application) addDefaultData(td *templateData, r *http.Request) *templateData {
if td == nil {
td = &templateData{}
}
if td.KvTables == nil {
td.KvTables = map[string]*kvTable{}
}
if _, exists := td.KvTables["General"]; !exists {
td.KvTables["General"] = func() *kvTable {
defaultKvTableCaches["General"].once.Do(func() {
defaultKvTableCaches["General"].cache = &kvTable{
Title: "General",
Values: map[string]string{
"Current Date": time.Now().Format(time.RFC3339),
"Remote Address": realip.FromRequest(r),
},
}
if app.config.Timeout > 0 {
defaultKvTableCaches["General"].cache.Values["Timeout after"] = fmt.Sprintf("%s seconds", strconv.FormatInt(app.config.Timeout, 10))
}
if app.config.MaxRequests > 0 {
defaultKvTableCaches["General"].cache.Values["Max requests"] = strconv.FormatInt(app.config.MaxRequests, 10)
}
})
return defaultKvTableCaches["General"].cache
}()
}
if _, exists := td.KvTables["Env"]; !exists {
td.KvTables["Env"] = func() *kvTable {
defaultKvTableCaches["Env"].once.Do(func() {
defaultKvTableCaches["Env"].cache = &kvTable{
Title: "Environment variables",
Values: map[string]string{},
}
for _, env := range os.Environ() {
if i := strings.IndexByte(env, '='); i >= 0 {
defaultKvTableCaches["Env"].cache.Values[env[:i]] = env[i+1:]
}
}
})
return defaultKvTableCaches["Env"].cache
}()
}
return td
}