-
-
Notifications
You must be signed in to change notification settings - Fork 355
/
http.go
888 lines (769 loc) · 22.6 KB
/
http.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
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
package app
import (
"bytes"
"context"
"crypto/sha1"
"encoding/json"
"fmt"
"io"
"net/http"
"os"
"path/filepath"
"sort"
"strconv"
"strings"
"sync"
"text/template"
"time"
"github.com/maxence-charriere/go-app/v10/pkg/errors"
)
const (
defaultThemeColor = "#2d2c2c"
)
// Handler configures an HTTP handler to serve HTML pages that initialize a
// Go WebAssembly (WASM) application along with its resources. It includes
// configurations for PWA features, offline support, auto-update, and more.
type Handler struct {
// Name specifies the display name of the web app, used where space permits.
Name string
// ShortName is an abbreviated app name for limited display areas.
ShortName string
// Icon represents the app icon used for PWA, favicon, and the default
// "not found" component. Attributes like crossorigin can be appended after
// a space.
Icon Icon
// BackgroundColor sets a placeholder background color for the app page
// before stylesheets load. Defaults to "#2d2c2c".
BackgroundColor string
// ThemeColor specifies the app's theme color, affecting OS-level UI elements
// like the PWA title bar. Defaults to "#2d2c2c".
ThemeColor string
// LoadingLabel shows text during page load, with "{progress}" for progress.
// Defaults to "{progress}%".
LoadingLabel string
// Lang defines the primary language of the app page. Defaults to "en".
Lang string
// Libraries are custom libraries to load with the page.
Libraries []Library
// Title sets the title of the app page.
Title string
// Description provides a summary of the page's content, used as default
// meta description and og:description.
Description string
// Domain specifies the domain name for resolving page metadata like
// 'og:url'.
Domain string
// Author lists the authors of the page.
Author string
// Keywords are words or phrases associated with the page.
Keywords []string
// Image specifies the default image path used by social networks.
// Attributes like crossorigin can be appended after a space.
Image string
// Styles lists CSS files for the page, supporting local and external
// resources. Attributes like crossorigin can be appended after a space.
Styles []string
// Fonts lists font files to preload, improving performance and visual
// readiness. Attributes like crossorigin can be appended after a space.
Fonts []string
// Scripts lists JavaScript files for the page. Attributes like crossorigin,
// async, and defer can be appended, separated with a space.
Scripts []string
// CacheableResources specifies extra static resources to cache for offline
// access. Icon, Styles and Scripts are already cached by default.
// Attributes like crossorigin can be appended after a space.
CacheableResources []string
// RawHeaders contains extra HTML headers for the page's <head> section.
RawHeaders []string
// HTML returns the page's HTML element. Defaults to app.Html().
HTML func() HTMLHtml
// Body returns the page's body element. Defaults to app.Body().
Body func() HTMLBody
// Env passes environment variables to the PWA. Note: Reserved keys
// (GOAPP_VERSION, GOAPP_GOAPP_STATIC_RESOURCES_URL) cannot be
// overridden and are used for internal configuration.
Env map[string]string
// InternalURLs lists URLs to open within the app, overriding default behavior
// for external domains.
InternalURLs []string
// Preconnect specifies origins to preconnect to, speeding up future loads.
// Attributes like crossorigin can be appended after a space.
Preconnect []string
// ProxyResources maps custom paths to static resources. /robots.txt,
// /sitemap.xml, and /ads.txt, which are proxied by default.
ProxyResources []ProxyResource
// Resources resolves paths for static resources, specifically handling
// paths prefixed with "/web/". Defaults to app.LocalDir("").
Resources ResourceResolver
// Version defines the app's version. It's crucial for determining if an
// update is available. Must be set in live environments to avoid recurring
// updates. Auto-generated by default for local development updates.
Version string
// WasmContentLength indicates the byte length of the WASM file for progress
// calculation. Falls back to WasmContentLengthHeader if unset.
WasmContentLength string
// WasmContentLengthHeader specifies the HTTP header for the WASM file's
// content length. Defaults to "Content-Length".
WasmContentLengthHeader string
// ServiceWorkerTemplate defines the app-worker.js template, defaulting
// to DefaultAppWorkerJS. Modifications are discouraged to avoid potential
// issues with go-app functionality.
ServiceWorkerTemplate string
once sync.Once
etag string
libraries map[string][]byte
proxyResources map[string]ProxyResource
cachedProxyResources *memoryCache
cachedPWAResources *memoryCache
}
func (h *Handler) init() {
h.initVersion()
h.initStaticResources()
h.initLibraries()
h.initLinks()
h.initServiceWorker()
h.initIcon()
h.initPWA()
h.initPageContent()
h.initPWAResources()
h.initProxyResources()
}
func (h *Handler) initVersion() {
if h.Version == "" {
t := time.Now().UTC().String()
h.Version = fmt.Sprintf(`%x`, sha1.Sum([]byte(t)))
}
h.etag = `"` + h.Version + `"`
}
func (h *Handler) initStaticResources() {
if h.Resources == nil {
h.Resources = LocalDir("")
}
}
func (h *Handler) initLibraries() {
libs := make(map[string][]byte)
for _, l := range h.Libraries {
path, styles := l.Styles()
if !strings.HasPrefix(path, "/") || len(styles) == 0 {
continue
}
libs[path] = []byte(styles)
}
h.libraries = libs
}
func (h *Handler) initLinks() {
styles := []string{"/app.css"}
for path := range h.libraries {
styles = append(styles, path)
}
h.Styles = append(styles, h.Styles...)
}
func (h *Handler) initServiceWorker() {
if h.ServiceWorkerTemplate == "" {
h.ServiceWorkerTemplate = DefaultAppWorkerJS
}
}
func (h *Handler) initIcon() {
if h.Icon.Default == "" {
h.Icon.Default = "https://raw.githubusercontent.com/maxence-charriere/go-app/master/docs/web/icon.png"
h.Icon.Large = "https://raw.githubusercontent.com/maxence-charriere/go-app/master/docs/web/icon.png"
}
if h.Icon.Maskable == "" {
h.Icon.Maskable = h.Icon.Default
}
if h.Icon.SVG == "" {
h.Icon.SVG = "https://raw.githubusercontent.com/maxence-charriere/go-app/master/docs/web/icon.svg"
}
}
func (h *Handler) initPWA() {
if h.Name == "" && h.ShortName == "" && h.Title == "" {
h.Name = "App PWA"
}
if h.ShortName == "" {
h.ShortName = h.Name
}
if h.Name == "" {
h.Name = h.ShortName
}
if h.BackgroundColor == "" {
h.BackgroundColor = defaultThemeColor
}
if h.ThemeColor == "" {
h.ThemeColor = defaultThemeColor
}
if h.Lang == "" {
h.Lang = "en"
}
if h.LoadingLabel == "" {
h.LoadingLabel = "{progress}%"
}
}
func (h *Handler) initPageContent() {
if h.HTML == nil {
h.HTML = Html
}
if h.Body == nil {
h.Body = Body
}
}
func (h *Handler) initPWAResources() {
h.cachedPWAResources = newMemoryCache(5)
h.cachedPWAResources.Set(cacheItem{
Path: "/wasm_exec.js",
ContentType: "application/javascript",
Body: []byte(wasmExecJS()),
})
h.cachedPWAResources.Set(cacheItem{
Path: "/app.js",
ContentType: "application/javascript",
Body: h.makeAppJS(),
})
h.cachedPWAResources.Set(cacheItem{
Path: "/app-worker.js",
ContentType: "application/javascript",
Body: h.makeAppWorkerJS(),
})
h.cachedPWAResources.Set(cacheItem{
Path: "/manifest.webmanifest",
ContentType: "application/manifest+json",
Body: h.makeManifestJSON(),
})
h.cachedPWAResources.Set(cacheItem{
Path: "/app.css",
ContentType: "text/css",
Body: []byte(appCSS),
})
}
func (h *Handler) makeAppJS() []byte {
if h.Env == nil {
h.Env = make(map[string]string)
}
internalURLs, _ := json.Marshal(h.InternalURLs)
h.Env["GOAPP_INTERNAL_URLS"] = string(internalURLs)
h.Env["GOAPP_VERSION"] = h.Version
h.Env["GOAPP_STATIC_RESOURCES_URL"] = h.Resources.Resolve("/web")
h.Env["GOAPP_ROOT_PREFIX"] = h.Resources.Resolve("/")
for k, v := range h.Env {
if err := os.Setenv(k, v); err != nil {
Log(errors.New("setting app env variable failed").
WithTag("name", k).
WithTag("value", v).
Wrap(err))
}
}
var b bytes.Buffer
if err := template.
Must(template.New("app.js").Parse(appJS)).
Execute(&b, struct {
Env string
LoadingLabel string
Wasm string
WasmContentLength string
WasmContentLengthHeader string
WorkerJS string
}{
Env: jsonString(h.Env),
LoadingLabel: h.LoadingLabel,
Wasm: h.Resources.Resolve("/web/app.wasm"),
WasmContentLength: h.WasmContentLength,
WasmContentLengthHeader: h.WasmContentLengthHeader,
WorkerJS: h.Resources.Resolve("/app-worker.js"),
}); err != nil {
panic(errors.New("initializing app.js failed").Wrap(err))
}
return b.Bytes()
}
func (h *Handler) makeAppWorkerJS() []byte {
resources := make(map[string]struct{})
setResources := func(res ...string) {
for _, r := range res {
if resource := parseHTTPResource(r); resource.URL != "" {
resources[resource.URL] = struct{}{}
}
}
}
setResources(
"/app.css",
"/app.js",
"/manifest.webmanifest",
"/wasm_exec.js",
"/",
"/web/app.wasm",
)
setResources(h.Icon.Default, h.Icon.Large, h.Icon.Maskable)
setResources(h.Styles...)
setResources(h.Fonts...)
setResources(h.Scripts...)
setResources(h.CacheableResources...)
resourcesTocache := make([]string, 0, len(resources))
for k := range resources {
resourcesTocache = append(resourcesTocache, h.Resources.Resolve(k))
}
sort.Slice(resourcesTocache, func(a, b int) bool {
return strings.Compare(resourcesTocache[a], resourcesTocache[b]) < 0
})
var b bytes.Buffer
if err := template.
Must(template.New("app-worker.js").Parse(h.ServiceWorkerTemplate)).
Execute(&b, struct {
Version string
ResourcesToCache string
}{
Version: h.Version,
ResourcesToCache: jsonString(resourcesTocache),
}); err != nil {
panic(errors.New("initializing app-worker.js failed").Wrap(err))
}
return b.Bytes()
}
func (h *Handler) makeManifestJSON() []byte {
scope := h.Resources.Resolve("/")
if scope != "/" && !strings.HasSuffix(scope, "/") {
scope += "/"
}
var b bytes.Buffer
if err := template.
Must(template.New("manifest.webmanifest").Parse(manifestJSON)).
Execute(&b, struct {
ShortName string
Name string
Description string
DefaultIcon string
LargeIcon string
SVGIcon string
MaskableIcon string
BackgroundColor string
ThemeColor string
Scope string
StartURL string
}{
ShortName: h.ShortName,
Name: h.Name,
Description: h.Description,
DefaultIcon: h.Resources.Resolve(h.Icon.Default),
LargeIcon: h.Resources.Resolve(h.Icon.Large),
SVGIcon: h.Resources.Resolve(h.Icon.SVG),
MaskableIcon: h.Resources.Resolve(h.Icon.Maskable),
BackgroundColor: h.BackgroundColor,
ThemeColor: h.ThemeColor,
Scope: scope,
StartURL: h.Resources.Resolve("/"),
}); err != nil {
panic(errors.New("initializing manifest.webmanifest failed").Wrap(err))
}
return b.Bytes()
}
func (h *Handler) initProxyResources() {
h.cachedProxyResources = newMemoryCache(len(h.ProxyResources))
resources := make(map[string]ProxyResource)
for _, r := range h.ProxyResources {
switch r.Path {
case "/wasm_exec.js",
"/goapp.js",
"/app.js",
"/app-worker.js",
"/manifest.json",
"/manifest.webmanifest",
"/app.css",
"/app.wasm",
"/goapp.wasm",
"/":
continue
default:
if strings.HasPrefix(r.Path, "/") && strings.HasPrefix(r.ResourcePath, "/web/") {
resources[r.Path] = r
}
}
}
if _, ok := resources["/robots.txt"]; !ok {
resources["/robots.txt"] = ProxyResource{
Path: "/robots.txt",
ResourcePath: "/web/robots.txt",
}
}
if _, ok := resources["/sitemap.xml"]; !ok {
resources["/sitemap.xml"] = ProxyResource{
Path: "/sitemap.xml",
ResourcePath: "/web/sitemap.xml",
}
}
if _, ok := resources["/ads.txt"]; !ok {
resources["/ads.txt"] = ProxyResource{
Path: "/ads.txt",
ResourcePath: "/web/ads.txt",
}
}
h.proxyResources = resources
}
func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
h.once.Do(h.init)
w.Header().Set("Cache-Control", "no-cache")
w.Header().Set("ETag", h.etag)
etag := r.Header.Get("If-None-Match")
if etag == h.etag {
w.WriteHeader(http.StatusNotModified)
return
}
path := r.URL.Path
if strings.HasPrefix(path, "/"+h.Version+"/") {
path = strings.TrimPrefix(path, "/"+h.Version)
}
fileHandler, isServingStaticResources := h.Resources.(http.Handler)
if isServingStaticResources && strings.HasPrefix(path, "/web/") {
fileHandler.ServeHTTP(w, r)
return
}
switch path {
case "/goapp.js":
path = "/app.js"
case "/manifest.json":
path = "/manifest.webmanifest"
case "/app.wasm", "/goapp.wasm":
if isServingStaticResources {
r2 := *r
r2.URL.Path = h.Resources.Resolve("/web/app.wasm")
fileHandler.ServeHTTP(w, &r2)
return
}
w.WriteHeader(http.StatusNotFound)
return
}
if res, ok := h.cachedPWAResources.Get(path); ok {
h.serveCachedItem(w, res)
return
}
if proxyResource, ok := h.proxyResources[path]; ok {
h.serveProxyResource(proxyResource, w, r)
return
}
if library, ok := h.libraries[path]; ok {
h.serveLibrary(w, r, library)
return
}
h.servePage(w, r)
}
func (h *Handler) serveCachedItem(w http.ResponseWriter, i cacheItem) {
w.Header().Set("Content-Length", strconv.Itoa(i.Len()))
w.Header().Set("Content-Type", i.ContentType)
if i.ContentEncoding != "" {
w.Header().Set("Content-Encoding", i.ContentEncoding)
}
w.WriteHeader(http.StatusOK)
w.Write(i.Body)
}
func (h *Handler) serveProxyResource(resource ProxyResource, w http.ResponseWriter, r *http.Request) {
var u string
if _, ok := h.Resources.(http.Handler); ok {
var protocol string
if r.TLS != nil {
protocol = "https://"
} else {
protocol = "http://"
}
u = protocol + r.Host + resource.ResourcePath
} else {
u = h.Resources.Resolve(resource.ResourcePath)
}
if i, ok := h.cachedProxyResources.Get(resource.Path); ok {
h.serveCachedItem(w, i)
return
}
res, err := http.Get(u)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Log(errors.New("getting proxy static resource failed").
WithTag("url", u).
WithTag("proxy-path", resource.Path).
WithTag("static-resource-path", resource.ResourcePath).
Wrap(err),
)
return
}
defer res.Body.Close()
if res.StatusCode != http.StatusOK {
w.WriteHeader(http.StatusNotFound)
return
}
body, err := io.ReadAll(res.Body)
if err != nil {
w.WriteHeader(http.StatusInternalServerError)
Log(errors.New("reading proxy static resource failed").
WithTag("url", u).
WithTag("proxy-path", resource.Path).
WithTag("static-resource-path", resource.ResourcePath).
Wrap(err),
)
return
}
item := cacheItem{
Path: resource.Path,
ContentType: res.Header.Get("Content-Type"),
ContentEncoding: res.Header.Get("Content-Encoding"),
Body: body,
}
h.cachedProxyResources.Set(item)
h.serveCachedItem(w, item)
}
func (h *Handler) servePage(w http.ResponseWriter, r *http.Request) {
if routed := routes.routed(r.URL.Path); !routed {
http.NotFound(w, r)
return
}
ctx := context.Background()
origin := *r.URL
origin.Scheme = "http"
page := makeRequestPage(&origin, h.Resources.Resolve)
page.SetTitle(h.Title)
page.SetLang(h.Lang)
page.SetDescription(h.Description)
page.SetAuthor(h.Author)
page.SetKeywords(h.Keywords...)
page.SetLoadingLabel(strings.ReplaceAll(h.LoadingLabel, "{progress}", "0"))
page.SetImage(h.Image)
engine := newEngine(ctx,
&routes,
h.Resources.Resolve,
&page,
actionHandlers,
)
engine.Navigate(page.URL(), false)
engine.ConsumeAll()
icon := h.Icon.SVG
if icon == "" {
icon = h.Icon.Default
}
var b bytes.Buffer
err := engine.Encode(&b, h.HTML().
Lang(page.Lang()).
privateBody(
Head().Body(
Meta().Charset("UTF-8"),
Meta().
Name("author").
Content(page.Author()),
Meta().
Name("description").
Content(page.Description()),
If(page.Keywords() != "", func() UI {
return Meta().
Name("keywords").
Content(page.Keywords())
}),
Meta().
Name("theme-color").
Content(h.ThemeColor),
Meta().
Name("viewport").
Content("width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0, viewport-fit=cover"),
Meta().
Property("og:url").
Content(resolveOGResource(h.Domain, h.Resources.Resolve(page.URL().Path))),
Meta().
Property("og:title").
Content(page.Title()),
Meta().
Property("og:description").
Content(page.Description()),
Meta().
Property("og:type").
Content("website"),
Meta().
Property("og:image").
Content(resolveOGResource(h.Domain, page.Image())),
Range(page.twitterCardMap).Map(func(k string) UI {
v := page.twitterCardMap[k]
if v == "" {
return nil
}
if k == "twitter:image" {
v = resolveOGResource(h.Domain, v)
}
return Meta().
Name(k).
Content(v)
}),
Title().Text(page.Title()),
Range(h.Preconnect).Slice(func(i int) UI {
if resource := parseHTTPResource(h.Preconnect[i]); resource.URL != "" {
return resource.toLink().Rel("preconnect")
}
return nil
}),
Range(h.Fonts).Slice(func(i int) UI {
if resource := parseHTTPResource(h.Fonts[i]); resource.URL != "" {
return resource.toLink().
Type("font/" + strings.TrimPrefix(filepath.Ext(resource.URL), ".")).
Rel("preload").
As("font")
}
return nil
}),
Range(page.Preloads()).Slice(func(i int) UI {
p := page.Preloads()[i]
if p.Href == "" || p.As == "" {
return nil
}
if resource := parseHTTPResource(p.Href); resource.URL != "" {
return resource.toLink().
Type(p.Type).
Rel("preload").
As(p.As).
FetchPriority(p.FetchPriority)
}
return nil
}),
Range(h.Styles).Slice(func(i int) UI {
if resource := parseHTTPResource(h.Styles[i]); resource.URL != "" {
return resource.toLink().
Type("text/css").
Rel("preload").
As("style")
}
return nil
}),
Link().
Rel("icon").
Href(icon),
Link().
Rel("apple-touch-icon").
Href(h.Icon.Maskable),
Link().
Rel("manifest").
Href("/manifest.webmanifest"),
Range(h.Styles).Slice(func(i int) UI {
if resource := parseHTTPResource(h.Styles[i]); resource.URL != "" {
return resource.toLink().
Type("text/css").
Rel("stylesheet")
}
return nil
}),
Script().
Defer(true).
Src("/wasm_exec.js"),
Script().
Defer(true).
Src("/app.js"),
Range(h.Scripts).Slice(func(i int) UI {
if resource := parseHTTPResource(h.Scripts[i]); resource.URL != "" {
return resource.toScript()
}
return nil
}),
Range(h.RawHeaders).Slice(func(i int) UI {
return Raw(h.RawHeaders[i])
}),
),
h.Body().privateBody(
Aside().
ID("app-wasm-loader").
Class("goapp-app-info").
Body(
Img().
ID("app-wasm-loader-icon").
Class("goapp-logo goapp-spin").
Alt("wasm loader icon").
Src(h.Icon.Default),
P().
ID("app-wasm-loader-label").
Class("goapp-label").
Text(page.loadingLabel),
),
),
))
if err != nil {
Log(errors.New("encoding html document failed").Wrap(err))
w.WriteHeader(http.StatusInternalServerError)
return
}
w.Header().Set("Content-Length", strconv.Itoa(b.Len()))
w.Header().Set("Content-Type", "text/html")
w.Write(b.Bytes())
}
func (h *Handler) serveLibrary(w http.ResponseWriter, r *http.Request, library []byte) {
w.Header().Set("Content-Length", strconv.Itoa(len(library)))
w.Header().Set("Content-Type", "text/css")
w.Write(library)
}
// Icon represents a square image utilized in various contexts, such as the
// application icon, favicon, and loading icon. Paths specified for icons
// are relative to the root directory unless stated otherwise.
type Icon struct {
// Default specifies the path or URL to a square image/png file with a
// dimension of 192x192 pixels. Represents the standard application icon.
Default string
// Large indicates the path or URL to a larger square image/png file,
// required to be 512x512 pixels. Used for high-resolution displays.
Large string
// SVG specifies the path or URL to an SVG file, providing vector-based
// imagery for scalable application icons. Ideal for responsive design.
SVG string
// Maskable specifies the path or URL to an adaptive icon designed for various
// operating system shapes. This icon must be a PNG image with 192x192 pixels.
//
// Used in PWA manifests and as meta tags for Apple browsers, these icons adapt
// to device or browser shape requirements, avoiding unsightly cropping.
//
// To convert existing icons to a maskable format, visit
// https://maskable.app/editor. This tool simplifies creating icons that meet
// maskable specifications.
//
// If not specified, Icon.Default is used as a fallback. Specifying a maskable
// icon enhances user experience on platforms supporting adaptive icons.
Maskable string
}
func isRemoteLocation(path string) bool {
return strings.HasPrefix(path, "https://") ||
strings.HasPrefix(path, "http://")
}
func isStaticResourcePath(path string) bool {
return strings.HasPrefix(path, "/web/") ||
strings.HasPrefix(path, "web/")
}
type httpResource struct {
URL string
LoadingMode string
CrossOrigin string
}
func (r httpResource) toLink() HTMLLink {
link := Link().Href(r.URL)
if r.CrossOrigin != "" {
link = link.CrossOrigin(strings.Trim(r.CrossOrigin, "true"))
}
return link
}
func (r httpResource) toScript() HTMLScript {
script := Script().Src(r.URL)
if r.CrossOrigin != "" {
script = script.CrossOrigin(strings.Trim(r.CrossOrigin, "true"))
}
switch r.LoadingMode {
case "defer":
script = script.Defer(true)
case "async":
script = script.Async(true)
}
return script
}
func parseHTTPResource(v string) httpResource {
var res httpResource
for _, elem := range strings.Split(v, " ") {
if elem = strings.TrimSpace(elem); elem == "" {
continue
}
elem = strings.ToLower(elem)
switch {
case elem == "crossorigin":
res.CrossOrigin = "true"
case strings.HasPrefix(elem, "crossorigin="):
res.CrossOrigin = strings.TrimPrefix(elem, "crossorigin=")
case elem == "defer":
res.LoadingMode = "defer"
case elem == "async":
res.LoadingMode = "async"
default:
res.URL = elem
}
}
return res
}