-
Notifications
You must be signed in to change notification settings - Fork 1
/
module.go
276 lines (234 loc) · 9.3 KB
/
module.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
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
package pugtemplate
import (
"context"
"errors"
"fmt"
"io"
"log"
"net/http"
"os"
"strings"
"flamingo.me/dingo"
"flamingo.me/flamingo/v3/framework/config"
"flamingo.me/flamingo/v3/framework/flamingo"
"flamingo.me/flamingo/v3/framework/systemendpoint"
"flamingo.me/flamingo/v3/framework/systemendpoint/domain"
"flamingo.me/flamingo/v3/framework/web"
"flamingo.me/pugtemplate/controllers"
"github.com/spf13/cobra"
"flamingo.me/pugtemplate/puganalyse"
"flamingo.me/pugtemplate/pugjs"
"flamingo.me/pugtemplate/templatefunctions"
)
type (
// Module for framework/pug_template
Module struct {
DefaultMux *http.ServeMux `inject:",optional"`
Basedir string `inject:"config:pug_template.basedir"`
Whitelist config.Slice `inject:"config:pug_template.cors_whitelist"`
CheckWebpack1337 bool `inject:"config:pug_template.check_webpack_1337"`
}
routes struct {
controller *DebugController
Basedir string `inject:"config:pug_template.basedir"`
Whitelist config.Slice `inject:"config:pug_template.cors_whitelist"`
CheckWebpack1337 bool `inject:"config:pug_template.check_webpack_1337"`
}
assetFileSystem struct {
fs http.FileSystem
}
)
// CueConfig for this module
func (m *Module) CueConfig() string {
return `
pug_template: {
trace?: bool
ratelimit: float
debug: bool
basedir: string
cors_whitelist: [...string]
check_webpack_1337: bool | *false
}
`
}
// Open - opens a given pass and returns a file
func (afs assetFileSystem) Open(path string) (http.File, error) {
path = strings.Replace(path, "/assets/", "", 1)
f, err := afs.fs.Open(path)
if err != nil {
return nil, err
}
s, err := f.Stat()
if err != nil || s.IsDir() {
return nil, errors.New("not allowed")
}
return f, nil
}
// Inject - inject func
func (r *routes) Inject(controller *DebugController) {
r.controller = controller
}
func assetHandler(whitelisted []string, check1337 bool) http.Handler {
whitelist := "!" + strings.Join(whitelisted, "!") + "!"
return http.HandlerFunc(func(rw http.ResponseWriter, req *http.Request) {
origin := req.Header.Get("Origin")
if strings.Contains(whitelist, "!"+origin+"!") || strings.Contains(whitelist, "!*!") {
rw.Header().Add("Access-Control-Allow-Origin", origin)
}
if check1337 {
if r, e := http.Get("http://localhost:1337" + req.RequestURI); e == nil {
copyHeaders(r, rw)
io.Copy(rw, r.Body)
return
}
}
http.FileServer(assetFileSystem{http.Dir("frontend/dist/")}).ServeHTTP(rw, req)
})
}
// Routes define routes
func (r *routes) Routes(registry *web.RouterRegistry) {
var whitelist []string
r.Whitelist.MapInto(&whitelist)
// trim whitelist of trailing slashes as urls can be configured that way
whitelist = trimTrailingSlashes(whitelist)
registry.MustRoute("/_pugtpl/debug", "pugtpl.debug")
registry.HandleGet("pugtpl.debug", r.controller.Get)
registry.HandleAny("_static", web.WrapHTTPHandler(http.StripPrefix("/static/", assetHandler(whitelist, r.CheckWebpack1337))))
registry.MustRoute("/static/*n", "_static")
registry.HandleData("page.template", func(ctx context.Context, _ *web.Request, _ web.RequestParams) interface{} {
return ctx.Value(pugjs.PageKey)
})
registry.MustRoute("/assets/*f", "_pugtemplate.assets")
registry.HandleAny("_pugtemplate.assets", web.WrapHTTPHandler(assetHandler(whitelist, r.CheckWebpack1337)))
}
// Configure DI
func (m *Module) Configure(injector *dingo.Injector) {
// We bind the Template Engine to the ChildSingleton level (in case there is different config handling
// We use the provider to make sure both are always the same injected type
injector.Bind(pugjs.Engine{}).In(dingo.ChildSingleton).ToProvider(pugjs.NewEngine)
injector.Bind((*flamingo.TemplateEngine)(nil)).In(dingo.ChildSingleton).ToProvider(
func(t *pugjs.Engine, i *dingo.Injector) flamingo.TemplateEngine {
return flamingo.TemplateEngine(t)
},
)
injector.Bind(new(pugjs.Startup)).In(dingo.Singleton)
injector.BindMap(new(domain.Handler), "/pugjs/ready").To(new(controllers.Ready))
if m.DefaultMux != nil {
var whitelist []string
m.Whitelist.MapInto(&whitelist)
m.DefaultMux.Handle("/assets/", assetHandler(whitelist, m.CheckWebpack1337))
}
injector.BindMap((*flamingo.TemplateFunc)(nil), "Math").To(templatefunctions.JsMath{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "Object").To(templatefunctions.JsObject{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "debug").To(templatefunctions.DebugFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "JSON").To(templatefunctions.JsJSON{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "startsWith").To(templatefunctions.StartsWithFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "truncate").To(templatefunctions.TruncateFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "stripTags").To(templatefunctions.StriptagsFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "capitalize").To(templatefunctions.CapitalizeFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "trim").To(templatefunctions.TrimFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "escapeHtml").To(templatefunctions.EscapeHTMLFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "parseInt").To(templatefunctions.ParseInt{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "asset").To(templatefunctions.AssetFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "data").To(templatefunctions.DataFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "get").To(templatefunctions.GetFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "tryUrl").To(templatefunctions.TryURLFunc{})
injector.BindMap((*flamingo.TemplateFunc)(nil), "url").To(templatefunctions.URLFunc{})
injector.BindMulti(new(cobra.Command)).ToProvider(templatecheckCmd)
web.BindRoutes(injector, new(routes))
flamingo.BindEventSubscriber(injector).To(pugjs.EventSubscriber{})
}
func templatecheckCmd() *cobra.Command {
return &cobra.Command{
Use: "templatecheck",
Short: "run opinionated checks in frontend/src: Checks atomic design system dependencies (PUG) and js dependencies conventions",
// Aliases: []string{"pugcheck"},
Run: AnalyseCommand(),
}
}
// AnalyseCommand func
func AnalyseCommand() func(cmd *cobra.Command, args []string) {
return func(cmd *cobra.Command, args []string) {
hasError := false
if _, err := os.Stat("frontend/src"); err == nil {
fmt.Println()
fmt.Println("Analyse Project Design System (PUG) in frontend/src")
fmt.Println("###################################################")
analyser := puganalyse.NewAtomicDesignAnalyser("frontend/src")
analyser.CheckPugImports()
hasError = analyser.HasError
fmt.Println(fmt.Sprintf("%v files checked", analyser.CheckCount))
fmt.Println()
fmt.Println("Analyse Project JS dependencies in frontend/src")
fmt.Println("###################################################")
jsanalyser := puganalyse.NewJsDependencyAnalyser("frontend/src")
jsanalyser.Check()
if !hasError {
hasError = analyser.HasError
}
fmt.Println(fmt.Sprintf("%v files checked", jsanalyser.CheckCount))
} else {
fmt.Println("Project Design System not found in folder frontend/src")
}
if _, err := os.Stat("frontend/src/shared"); err == nil {
fmt.Println()
log.Printf("Analyse Shared Design System (PUG) in frontend/src/shared")
fmt.Println("###################################################")
analyser := puganalyse.NewAtomicDesignAnalyser("frontend/src/shared")
analyser.CheckPugImports()
fmt.Println(fmt.Sprintf("%v files checked", analyser.CheckCount))
if !hasError {
hasError = analyser.HasError
}
fmt.Println()
fmt.Println("Analyse Shared JS dependencies in frontend/src/shared")
fmt.Println("###################################################")
jsanalyser := puganalyse.NewJsDependencyAnalyser("frontend/src/shared")
jsanalyser.Check()
if !hasError {
hasError = analyser.HasError
}
fmt.Println(fmt.Sprintf("%v files checked", jsanalyser.CheckCount))
} else {
fmt.Println("No shared Design System not found in folder frontend/src/shared")
}
if hasError {
os.Exit(-1)
}
}
}
// Depends on other modules
func (m *Module) Depends() []dingo.Module {
return []dingo.Module{
new(systemendpoint.Module),
}
}
// DefaultConfig for setting pug-related config options
func (m *Module) DefaultConfig() config.Map {
return config.Map{
"pug_template.basedir": "frontend/dist",
"pug_template.debug": true,
"pug_template.cors_whitelist": config.Slice{"http://localhost:3210"},
"pug_template.ratelimit": float64(8),
"imageservice.base_url": "-",
"imageservice.secret": "-",
"flamingo.opencensus.tracing.sampler.blacklist": config.Slice{"/static", "/assets"},
"pug_template.check_webpack_1337": false,
}
}
func copyHeaders(r *http.Response, w http.ResponseWriter) {
for key, values := range r.Header {
for _, value := range values {
w.Header().Add(key, value)
}
}
}
// trimTrailingSlashes remove trailing slashes from configured whitelist urls
// in case they have been configured
func trimTrailingSlashes(whitelist []string) []string {
result := make([]string, len(whitelist))
for i, entry := range whitelist {
result[i] = strings.TrimRight(entry, "/")
}
return result
}