This repository has been archived by the owner on Jul 12, 2022. It is now read-only.
-
Notifications
You must be signed in to change notification settings - Fork 27
/
page.go
211 lines (180 loc) · 4.68 KB
/
page.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
package gosaas
import (
"context"
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"log"
"net/http"
"os"
"path"
"strconv"
"github.com/dstpierre/gosaas/model"
)
var (
pageTemplates *template.Template
languagePacks map[string]map[string]string
)
func init() {
loadTemplates()
loadLanguagePacks()
}
func loadTemplates() {
var tmpl []string
files, err := ioutil.ReadDir("./templates")
if err != nil {
if os.IsNotExist(err) == false {
log.Fatal("unable to load templates", err)
}
return
}
for _, f := range files {
tmpl = append(tmpl, path.Join("./templates", f.Name()))
}
t, err := template.New("").Funcs(template.FuncMap{
"translate": Translate,
"translatef": Translatef,
"money": func(amount int) string {
m := float64(amount) / 100.0
return fmt.Sprintf("%.2f $", m)
},
}).ParseFiles(tmpl...)
if err != nil {
log.Fatal("error while parsing templates", err)
}
pageTemplates = t
}
// ServePage will render and respond with an HTML template.ServePage
//
// HTML templates should be saved into a directory named templates.ServePage
//
// Example usage:
//
// func handler(w http.ResponseWriter, r *http.Request) {
// data := HomePage{Title: "Hello world!"}
// gosaas.ServePage(w, r, "index.html", data)
// }
func ServePage(w http.ResponseWriter, r *http.Request, name string, data interface{}) {
t := pageTemplates.Lookup(name)
if err := t.Execute(w, data); err != nil {
fmt.Println("error while rendering the template ", err)
}
logRequest(r, http.StatusOK)
}
func loadLanguagePacks() {
languagePacks = make(map[string]map[string]string)
files, err := ioutil.ReadDir("./languagepacks")
if err != nil {
log.Println("unable to load language packs: ", err)
return
}
var pack = new(struct {
Language string `json:"lang"`
Keys []struct {
Key string `json:"key"`
Value string `json:"value"`
} `json:"keys"`
})
for _, f := range files {
b, err := ioutil.ReadFile(path.Join("./languagepacks", f.Name()))
if err != nil {
log.Fatal("unable to read language pack: ", f.Name(), ": ", err)
}
if err := json.Unmarshal(b, &pack); err != nil {
log.Fatal("unable to parse language pack: ", f.Name(), ": ", err)
}
values := make(map[string]string)
for _, k := range pack.Keys {
values[k.Key] = k.Value
}
languagePacks[pack.Language] = values
}
}
// Translate finds a key in a language pack file (saved in directory named languagepack)
// and return the value as template.HTML so it's safe to use HTML inside the language pack file.Translate
//
// The language pack file are simple JSON file named lng.json like en.json:
//
// {
// "lang": "en",
// "keys": [
// {"key": "landing-title", "value": "Welcome to my site"}
// ]
// }
func Translate(lng, key string) template.HTML {
if s, ok := languagePacks[lng][key]; ok {
return template.HTML(s)
}
return template.HTML(fmt.Sprintf("key %s not found", key))
}
// Translatef finds a translation key and substitute the formatting parameters.
func Translatef(lng, key string, a ...interface{}) string {
if s, ok := languagePacks[lng][key]; ok {
return fmt.Sprintf(s, a...)
}
return fmt.Sprintf("key %s not found", key)
}
// BUG(dom): This needs more thinking...
func ExtractLimitAndOffset(r *http.Request) (limit int, offset int) {
limit = 50
offset = 0
p := r.URL.Query().Get("limit")
if len(p) > 0 {
i, err := strconv.Atoi(p)
if err == nil {
limit = i
}
}
p = r.URL.Query().Get("offset")
if len(p) > 0 {
i, err := strconv.Atoi(p)
if err == nil {
offset = i
}
}
return
}
// ViewData is the base data needed for all pages to render.
//
// It will automatically get the user's language, role and if there's an alert
// to display. You can view this a a wrapper around what you would have sent to the
// page being redered.
type ViewData struct {
Language string
Role model.Roles
Alert *Notification
Data interface{}
}
// Notification can be used to display alert to the user in an HTML template.
type Notification struct {
Title template.HTML
Message template.HTML
IsSuccess bool
IsError bool
IsWarning bool
}
func getLanguage(ctx context.Context) string {
lng, ok := ctx.Value(ContextLanguage).(string)
if !ok {
lng = "en"
}
return lng
}
func getRole(ctx context.Context) model.Roles {
auth, ok := ctx.Value(ContextAuth).(Auth)
if !ok {
return model.RolePublic
}
return auth.Role
}
// CreateViewData wraps the data into a ViewData type where the language, role and
// notification will be automatically added along side the data.
func CreateViewData(ctx context.Context, alert *Notification, data interface{}) ViewData {
return ViewData{
Alert: alert,
Data: data,
Language: getLanguage(ctx),
Role: getRole(ctx),
}
}