http.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890
  1. package app
  2. import (
  3. "bytes"
  4. "context"
  5. "crypto/sha1"
  6. "encoding/json"
  7. "fmt"
  8. "io"
  9. "net/http"
  10. "os"
  11. "reflect"
  12. "runtime"
  13. "sort"
  14. "strconv"
  15. "strings"
  16. "sync"
  17. "text/template"
  18. "time"
  19. "github.com/maxence-charriere/go-app/v9/pkg/errors"
  20. )
  21. const (
  22. defaultThemeColor = "#2d2c2c"
  23. defaultPreRenderCacheSize = 8000000
  24. defaultPreRenderCacheTTL = time.Hour * 24
  25. )
  26. // Handler is an HTTP handler that serves an HTML page that loads a Go wasm app
  27. // and its resources.
  28. type Handler struct {
  29. // The name of the web application as it is usually displayed to the user.
  30. Name string
  31. // The name of the web application displayed to the user when there is not
  32. // enough space to display Name.
  33. ShortName string
  34. // The icon that is used for the PWA, favicon, loading and default not
  35. // found component.
  36. Icon Icon
  37. // A placeholder background color for the application page to display before
  38. // its stylesheets are loaded.
  39. //
  40. // Default: #2d2c2c.
  41. BackgroundColor string
  42. // The theme color for the application. This affects how the OS displays the
  43. // app (e.g., PWA title bar or Android's task switcher).
  44. //
  45. // DEFAULT: #2d2c2c.
  46. ThemeColor string
  47. // The text displayed while loading a page. Load progress can be inserted by
  48. // including "{progress}" in the loading label.
  49. //
  50. // DEFAULT: "{progress}%".
  51. LoadingLabel string
  52. // The page language.
  53. //
  54. // DEFAULT: en.
  55. Lang string
  56. // The page title.
  57. Title string
  58. // The page description.
  59. Description string
  60. // The page authors.
  61. Author string
  62. // The page keywords.
  63. Keywords []string
  64. // The path of the default image that is used by social networks when
  65. // linking the app.
  66. Image string
  67. // The paths or urls of the CSS files to use with the page.
  68. //
  69. // eg:
  70. // app.Handler{
  71. // Styles: []string{
  72. // "/web/test.css", // Static resource
  73. // "https://foo.com/test.css", // External resource
  74. // },
  75. // },
  76. Styles []string
  77. // The paths or urls of the JavaScript files to use with the page.
  78. //
  79. // eg:
  80. // app.Handler{
  81. // Scripts: []string{
  82. // "/web/test.js", // Static resource
  83. // "https://foo.com/test.js", // External resource
  84. // },
  85. // },
  86. Scripts []string
  87. // The path of the static resources that the browser is caching in order to
  88. // provide offline mode.
  89. //
  90. // Note that Icon, Styles and Scripts are already cached by default.
  91. //
  92. // Paths are relative to the root directory.
  93. CacheableResources []string
  94. // Additional headers to be added in head element.
  95. RawHeaders []string
  96. // The page HTML element.
  97. //
  98. // Default: Html().
  99. HTML func() HTMLHtml
  100. // The page body element.
  101. //
  102. // Note that the lang attribute is always overridden by the Handler.Lang
  103. // value.
  104. //
  105. // Default: Body().
  106. Body func() HTMLBody
  107. // The interval between each app auto-update while running in a web browser.
  108. // Zero or negative values deactivates the auto-update mechanism.
  109. //
  110. // Default is 0.
  111. AutoUpdateInterval time.Duration
  112. // The environment variables that are passed to the progressive web app.
  113. //
  114. // Reserved keys:
  115. // - GOAPP_VERSION
  116. // - GOAPP_GOAPP_STATIC_RESOURCES_URL
  117. Env Environment
  118. // The URLs that are launched in the app tab or window.
  119. //
  120. // By default, URLs with a different domain are launched in another tab.
  121. // Specifying internal URLs is to override that behavior. A good use case
  122. // would be the URL for an OAuth authentication.
  123. InternalURLs []string
  124. // The cache that stores pre-rendered pages.
  125. //
  126. // Default: A LRU cache that keeps pages up to 24h and have a maximum size
  127. // of 8MB.
  128. PreRenderCache PreRenderCache
  129. // The static resources that are accessible from custom paths. Files that
  130. // are proxied by default are /robots.txt, /sitemap.xml and /ads.txt.
  131. ProxyResources []ProxyResource
  132. // The resource provider that provides static resources. Static resources
  133. // are always accessed from a path that starts with "/web/".
  134. //
  135. // eg:
  136. // "/web/main.css"
  137. //
  138. // Default: LocalDir("")
  139. Resources ResourceProvider
  140. // The version number. This is used in order to update the PWA application
  141. // in the browser. It must be set when deployed on a live system in order to
  142. // prevent recurring updates.
  143. //
  144. // Default: Auto-generated in order to trigger pwa update on a local
  145. // development system.
  146. Version string
  147. // The HTTP header to retrieve the WebAssembly file content length.
  148. //
  149. // Content length finding falls back to the Content-Length HTTP header when
  150. // no content length is found with the defined header.
  151. WasmContentLengthHeader string
  152. // The template used to generate app-worker.js. The template follows the
  153. // text/template package model.
  154. //
  155. // By default set to DefaultAppWorkerJS, changing the template have very
  156. // high chances to mess up go-app usage. Any issue related to a custom app
  157. // worker template is not supported and will be closed.
  158. ServiceWorkerTemplate string
  159. once sync.Once
  160. etag string
  161. pwaResources PreRenderCache
  162. proxyResources map[string]ProxyResource
  163. }
  164. func (h *Handler) init() {
  165. h.initVersion()
  166. h.initStaticResources()
  167. h.initImage()
  168. h.initStyles()
  169. h.initScripts()
  170. h.initServiceWorker()
  171. h.initCacheableResources()
  172. h.initIcon()
  173. h.initPWA()
  174. h.initPageContent()
  175. h.initPreRenderedResources()
  176. h.initProxyResources()
  177. }
  178. func (h *Handler) initVersion() {
  179. if h.Version == "" {
  180. t := time.Now().UTC().String()
  181. h.Version = fmt.Sprintf(`%x`, sha1.Sum([]byte(t)))
  182. }
  183. h.etag = `"` + h.Version + `"`
  184. }
  185. func (h *Handler) initStaticResources() {
  186. if h.Resources == nil {
  187. h.Resources = LocalDir("")
  188. }
  189. }
  190. func (h *Handler) initImage() {
  191. if h.Image != "" {
  192. h.Image = h.resolveStaticPath(h.Image)
  193. }
  194. }
  195. func (h *Handler) initStyles() {
  196. for i, path := range h.Styles {
  197. h.Styles[i] = h.resolveStaticPath(path)
  198. }
  199. }
  200. func (h *Handler) initScripts() {
  201. for i, path := range h.Scripts {
  202. h.Scripts[i] = h.resolveStaticPath(path)
  203. }
  204. }
  205. func (h *Handler) initServiceWorker() {
  206. if h.ServiceWorkerTemplate == "" {
  207. h.ServiceWorkerTemplate = DefaultAppWorkerJS
  208. }
  209. }
  210. func (h *Handler) initCacheableResources() {
  211. for i, path := range h.CacheableResources {
  212. h.CacheableResources[i] = h.resolveStaticPath(path)
  213. }
  214. }
  215. func (h *Handler) initIcon() {
  216. if h.Icon.Default == "" {
  217. h.Icon.Default = "https://storage.googleapis.com/murlok-github/icon-192.png"
  218. h.Icon.Large = "https://storage.googleapis.com/murlok-github/icon-512.png"
  219. }
  220. if h.Icon.AppleTouch == "" {
  221. h.Icon.AppleTouch = h.Icon.Default
  222. }
  223. h.Icon.Default = h.resolveStaticPath(h.Icon.Default)
  224. h.Icon.Large = h.resolveStaticPath(h.Icon.Large)
  225. h.Icon.AppleTouch = h.resolveStaticPath(h.Icon.AppleTouch)
  226. }
  227. func (h *Handler) initPWA() {
  228. if h.Name == "" && h.ShortName == "" && h.Title == "" {
  229. h.Name = "App PWA"
  230. }
  231. if h.ShortName == "" {
  232. h.ShortName = h.Name
  233. }
  234. if h.Name == "" {
  235. h.Name = h.ShortName
  236. }
  237. if h.BackgroundColor == "" {
  238. h.BackgroundColor = defaultThemeColor
  239. }
  240. if h.ThemeColor == "" {
  241. h.ThemeColor = defaultThemeColor
  242. }
  243. if h.Lang == "" {
  244. h.Lang = "en"
  245. }
  246. if h.LoadingLabel == "" {
  247. h.LoadingLabel = "{progress}%"
  248. }
  249. }
  250. func (h *Handler) initPageContent() {
  251. if h.HTML == nil {
  252. h.HTML = Html
  253. }
  254. if h.Body == nil {
  255. h.Body = Body
  256. }
  257. }
  258. func (h *Handler) initPreRenderedResources() {
  259. h.pwaResources = newPreRenderCache(5)
  260. ctx := context.TODO()
  261. h.pwaResources.Set(ctx, PreRenderedItem{
  262. Path: "/wasm_exec.js",
  263. ContentType: "application/javascript",
  264. Body: []byte(wasmExecJS),
  265. })
  266. h.pwaResources.Set(ctx, PreRenderedItem{
  267. Path: "/app.js",
  268. ContentType: "application/javascript",
  269. Body: h.makeAppJS(),
  270. })
  271. h.pwaResources.Set(ctx, PreRenderedItem{
  272. Path: "/app-worker.js",
  273. ContentType: "application/javascript",
  274. Body: h.makeAppWorkerJS(),
  275. })
  276. h.pwaResources.Set(ctx, PreRenderedItem{
  277. Path: "/manifest.webmanifest",
  278. ContentType: "application/manifest+json",
  279. Body: h.makeManifestJSON(),
  280. })
  281. h.pwaResources.Set(ctx, PreRenderedItem{
  282. Path: "/app.css",
  283. ContentType: "text/css",
  284. Body: []byte(appCSS),
  285. })
  286. if h.PreRenderCache == nil {
  287. h.PreRenderCache = NewPreRenderLRUCache(
  288. defaultPreRenderCacheSize,
  289. defaultPreRenderCacheTTL,
  290. )
  291. }
  292. }
  293. func (h *Handler) makeAppJS() []byte {
  294. if h.Env == nil {
  295. h.Env = make(map[string]string)
  296. }
  297. internalURLs, _ := json.Marshal(h.InternalURLs)
  298. h.Env["GOAPP_INTERNAL_URLS"] = string(internalURLs)
  299. h.Env["GOAPP_VERSION"] = h.Version
  300. h.Env["GOAPP_STATIC_RESOURCES_URL"] = h.Resources.Static()
  301. h.Env["GOAPP_ROOT_PREFIX"] = h.Resources.Package()
  302. for k, v := range h.Env {
  303. if err := os.Setenv(k, v); err != nil {
  304. Log(errors.New("setting app env variable failed").
  305. Tag("name", k).
  306. Tag("value", v).
  307. Wrap(err))
  308. }
  309. }
  310. var b bytes.Buffer
  311. if err := template.
  312. Must(template.New("app.js").Parse(appJS)).
  313. Execute(&b, struct {
  314. Env string
  315. LoadingLabel string
  316. Wasm string
  317. WasmContentLengthHeader string
  318. WorkerJS string
  319. AutoUpdateInterval int64
  320. }{
  321. Env: jsonString(h.Env),
  322. LoadingLabel: h.LoadingLabel,
  323. Wasm: h.Resources.AppWASM(),
  324. WasmContentLengthHeader: h.WasmContentLengthHeader,
  325. WorkerJS: h.resolvePackagePath("/app-worker.js"),
  326. AutoUpdateInterval: h.AutoUpdateInterval.Milliseconds(),
  327. }); err != nil {
  328. panic(errors.New("initializing app.js failed").Wrap(err))
  329. }
  330. return b.Bytes()
  331. }
  332. func (h *Handler) makeAppWorkerJS() []byte {
  333. resources := make(map[string]struct{})
  334. setResources := func(res ...string) {
  335. for _, r := range res {
  336. if r == "" {
  337. continue
  338. }
  339. resources[r] = struct{}{}
  340. }
  341. }
  342. setResources(
  343. h.resolvePackagePath("/app.css"),
  344. h.resolvePackagePath("/app.js"),
  345. h.resolvePackagePath("/manifest.webmanifest"),
  346. h.resolvePackagePath("/wasm_exec.js"),
  347. h.resolvePackagePath("/"),
  348. h.Resources.AppWASM(),
  349. )
  350. setResources(h.Icon.Default, h.Icon.Large, h.Icon.AppleTouch)
  351. setResources(h.Styles...)
  352. setResources(h.Scripts...)
  353. setResources(h.CacheableResources...)
  354. resourcesTocache := make([]string, 0, len(resources))
  355. for k := range resources {
  356. resourcesTocache = append(resourcesTocache, k)
  357. }
  358. sort.Slice(resourcesTocache, func(a, b int) bool {
  359. return strings.Compare(resourcesTocache[a], resourcesTocache[b]) < 0
  360. })
  361. var b bytes.Buffer
  362. if err := template.
  363. Must(template.New("app-worker.js").Parse(h.ServiceWorkerTemplate)).
  364. Execute(&b, struct {
  365. Version string
  366. ResourcesToCache string
  367. }{
  368. Version: h.Version,
  369. ResourcesToCache: jsonString(resourcesTocache),
  370. }); err != nil {
  371. panic(errors.New("initializing app-worker.js failed").Wrap(err))
  372. }
  373. return b.Bytes()
  374. }
  375. func (h *Handler) makeManifestJSON() []byte {
  376. normalize := func(s string) string {
  377. if !strings.HasPrefix(s, "/") {
  378. s = "/" + s
  379. }
  380. if !strings.HasSuffix(s, "/") {
  381. s += "/"
  382. }
  383. return s
  384. }
  385. var b bytes.Buffer
  386. if err := template.
  387. Must(template.New("manifest.webmanifest").Parse(manifestJSON)).
  388. Execute(&b, struct {
  389. ShortName string
  390. Name string
  391. Description string
  392. DefaultIcon string
  393. LargeIcon string
  394. BackgroundColor string
  395. ThemeColor string
  396. Scope string
  397. StartURL string
  398. }{
  399. ShortName: h.ShortName,
  400. Name: h.Name,
  401. Description: h.Description,
  402. DefaultIcon: h.Icon.Default,
  403. LargeIcon: h.Icon.Large,
  404. BackgroundColor: h.BackgroundColor,
  405. ThemeColor: h.ThemeColor,
  406. Scope: normalize(h.Resources.Package()),
  407. StartURL: normalize(h.Resources.Package()),
  408. }); err != nil {
  409. panic(errors.New("initializing manifest.webmanifest failed").Wrap(err))
  410. }
  411. return b.Bytes()
  412. }
  413. func (h *Handler) initProxyResources() {
  414. resources := make(map[string]ProxyResource)
  415. for _, r := range h.ProxyResources {
  416. switch r.Path {
  417. case "/wasm_exec.js",
  418. "/goapp.js",
  419. "/app.js",
  420. "/app-worker.js",
  421. "/manifest.json",
  422. "/manifest.webmanifest",
  423. "/app.css",
  424. "/app.wasm",
  425. "/goapp.wasm",
  426. "/":
  427. continue
  428. default:
  429. if strings.HasPrefix(r.Path, "/") && strings.HasPrefix(r.ResourcePath, "/web/") {
  430. resources[r.Path] = r
  431. }
  432. }
  433. }
  434. if _, ok := resources["/robots.txt"]; !ok {
  435. resources["/robots.txt"] = ProxyResource{
  436. Path: "/robots.txt",
  437. ResourcePath: "/web/robots.txt",
  438. }
  439. }
  440. if _, ok := resources["/sitemap.xml"]; !ok {
  441. resources["/sitemap.xml"] = ProxyResource{
  442. Path: "/sitemap.xml",
  443. ResourcePath: "/web/sitemap.xml",
  444. }
  445. }
  446. if _, ok := resources["/ads.txt"]; !ok {
  447. resources["/ads.txt"] = ProxyResource{
  448. Path: "/ads.txt",
  449. ResourcePath: "/web/ads.txt",
  450. }
  451. }
  452. h.proxyResources = resources
  453. }
  454. func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
  455. h.once.Do(h.init)
  456. w.Header().Set("Cache-Control", "no-cache")
  457. w.Header().Set("ETag", h.etag)
  458. etag := r.Header.Get("If-None-Match")
  459. if etag == h.etag {
  460. w.WriteHeader(http.StatusNotModified)
  461. return
  462. }
  463. path := r.URL.Path
  464. fileHandler, isServingStaticResources := h.Resources.(http.Handler)
  465. if isServingStaticResources && strings.HasPrefix(path, "/web/") {
  466. fileHandler.ServeHTTP(w, r)
  467. return
  468. }
  469. switch path {
  470. case "/goapp.js":
  471. path = "/app.js"
  472. case "/manifest.json":
  473. path = "/manifest.webmanifest"
  474. case "/app.wasm", "/goapp.wasm":
  475. if isServingStaticResources {
  476. r2 := *r
  477. r2.URL.Path = h.Resources.AppWASM()
  478. fileHandler.ServeHTTP(w, &r2)
  479. return
  480. }
  481. w.WriteHeader(http.StatusNotFound)
  482. return
  483. }
  484. if res, ok := h.pwaResources.Get(r.Context(), path); ok {
  485. h.servePreRenderedItem(w, res)
  486. return
  487. }
  488. if res, ok := h.PreRenderCache.Get(r.Context(), path); ok {
  489. h.servePreRenderedItem(w, res)
  490. return
  491. }
  492. if proxyResource, ok := h.proxyResources[path]; ok {
  493. h.serveProxyResource(proxyResource, w, r)
  494. return
  495. }
  496. h.servePage(w, r)
  497. }
  498. func (h *Handler) servePreRenderedItem(w http.ResponseWriter, r PreRenderedItem) {
  499. w.Header().Set("Content-Length", strconv.Itoa(r.Size()))
  500. w.Header().Set("Content-Type", r.ContentType)
  501. if r.ContentEncoding != "" {
  502. w.Header().Set("Content-Encoding", r.ContentEncoding)
  503. }
  504. w.WriteHeader(http.StatusOK)
  505. w.Write(r.Body)
  506. }
  507. func (h *Handler) serveProxyResource(resource ProxyResource, w http.ResponseWriter, r *http.Request) {
  508. var u string
  509. if _, ok := h.Resources.(http.Handler); ok {
  510. var protocol string
  511. if r.TLS != nil {
  512. protocol = "https://"
  513. } else {
  514. protocol = "http://"
  515. }
  516. u = protocol + r.Host + resource.ResourcePath
  517. } else {
  518. u = h.Resources.Static() + resource.ResourcePath
  519. }
  520. res, err := http.Get(u)
  521. if err != nil {
  522. w.WriteHeader(http.StatusInternalServerError)
  523. Log(errors.New("getting proxy static resource failed").
  524. Tag("url", u).
  525. Tag("proxy-path", resource.Path).
  526. Tag("static-resource-path", resource.ResourcePath).
  527. Wrap(err),
  528. )
  529. return
  530. }
  531. defer res.Body.Close()
  532. if res.StatusCode != http.StatusOK {
  533. w.WriteHeader(http.StatusNotFound)
  534. return
  535. }
  536. body, err := io.ReadAll(res.Body)
  537. if err != nil {
  538. w.WriteHeader(http.StatusInternalServerError)
  539. Log(errors.New("reading proxy static resource failed").
  540. Tag("url", u).
  541. Tag("proxy-path", resource.Path).
  542. Tag("static-resource-path", resource.ResourcePath).
  543. Wrap(err),
  544. )
  545. return
  546. }
  547. item := PreRenderedItem{
  548. Path: resource.Path,
  549. ContentType: res.Header.Get("Content-Type"),
  550. ContentEncoding: res.Header.Get("Content-Encoding"),
  551. Body: body,
  552. }
  553. h.PreRenderCache.Set(r.Context(), item)
  554. h.servePreRenderedItem(w, item)
  555. }
  556. func (h *Handler) servePage(w http.ResponseWriter, r *http.Request) {
  557. content, ok := routes.createComponent(r.URL.Path)
  558. if !ok {
  559. http.NotFound(w, r)
  560. return
  561. }
  562. url := *r.URL
  563. url.Host = r.Host
  564. url.Scheme = "http"
  565. var page requestPage
  566. page.SetTitle(h.Title)
  567. page.SetLang(h.Lang)
  568. page.SetDescription(h.Description)
  569. page.SetAuthor(h.Author)
  570. page.SetKeywords(h.Keywords...)
  571. page.SetLoadingLabel(strings.ReplaceAll(h.LoadingLabel, "{progress}", "0"))
  572. page.SetImage(h.Image)
  573. page.url = &url
  574. disp := engine{
  575. Page: &page,
  576. IsServerSide: true,
  577. StaticResourceResolver: h.resolveStaticPath,
  578. ActionHandlers: actionHandlers,
  579. }
  580. body := h.Body().privateBody(
  581. Div().Body(
  582. Aside().
  583. ID("app-wasm-loader").
  584. Class("goapp-app-info").
  585. Body(
  586. Img().
  587. ID("app-wasm-loader-icon").
  588. Class("goapp-logo goapp-spin").
  589. Src(h.Icon.Default),
  590. P().
  591. ID("app-wasm-loader-label").
  592. Class("goapp-label").
  593. Text(page.loadingLabel),
  594. ),
  595. Div().ID("app-pre-render").Body(content),
  596. ),
  597. )
  598. if err := mount(&disp, body); err != nil {
  599. panic(errors.New("mounting pre-rendering container failed").
  600. Tag("server-side", disp.isServerSide()).
  601. Tag("body-type", reflect.TypeOf(disp.Body)).
  602. Wrap(err))
  603. }
  604. disp.Body = body
  605. disp.init()
  606. defer disp.Close()
  607. disp.PreRender()
  608. for len(disp.dispatches) != 0 {
  609. disp.Consume()
  610. disp.Wait()
  611. }
  612. var b bytes.Buffer
  613. b.WriteString("<!DOCTYPE html>\n")
  614. PrintHTML(&b, h.HTML().
  615. Lang(page.Lang()).
  616. privateBody(
  617. Head().Body(
  618. Meta().Charset("UTF-8"),
  619. Meta().
  620. Name("author").
  621. Content(page.Author()),
  622. Meta().
  623. Name("description").
  624. Content(page.Description()),
  625. Meta().
  626. Name("keywords").
  627. Content(page.Keywords()),
  628. Meta().
  629. Name("theme-color").
  630. Content(h.ThemeColor),
  631. Meta().
  632. Name("viewport").
  633. Content("width=device-width, initial-scale=1, maximum-scale=1, user-scalable=0, viewport-fit=cover"),
  634. Meta().
  635. Property("og:url").
  636. Content(page.URL().String()),
  637. Meta().
  638. Property("og:title").
  639. Content(page.Title()),
  640. Meta().
  641. Property("og:description").
  642. Content(page.Description()),
  643. Meta().
  644. Property("og:type").
  645. Content("website"),
  646. Meta().
  647. Property("og:image").
  648. Content(page.Image()),
  649. Title().Text(page.Title()),
  650. Link().
  651. Rel("icon").
  652. Href(h.Icon.Default),
  653. If(h.Icon.Mask != "",
  654. Link().
  655. Rel("mask-icon").
  656. Attr("color", h.Icon.MaskColor).
  657. Href(h.Icon.Mask),
  658. ),
  659. Link().
  660. Rel("apple-touch-icon").
  661. Href(h.Icon.AppleTouch),
  662. Link().
  663. Rel("manifest").
  664. Href(h.resolvePackagePath("/manifest.webmanifest")),
  665. Link().
  666. Type("text/css").
  667. Rel("stylesheet").
  668. Href(h.resolvePackagePath("/app.css")),
  669. Script().
  670. Defer(true).
  671. Src(h.resolvePackagePath("/wasm_exec.js")),
  672. Script().
  673. Defer(true).
  674. Src(h.resolvePackagePath("/app.js")),
  675. Range(h.Styles).Slice(func(i int) UI {
  676. return Link().
  677. Type("text/css").
  678. Rel("stylesheet").
  679. Href(h.Styles[i])
  680. }),
  681. Range(h.Scripts).Slice(func(i int) UI {
  682. return Script().
  683. Defer(true).
  684. Src(h.Scripts[i])
  685. }),
  686. Range(h.RawHeaders).Slice(func(i int) UI {
  687. return Raw(h.RawHeaders[i])
  688. }),
  689. ),
  690. body,
  691. ))
  692. item := PreRenderedItem{
  693. Path: page.URL().Path,
  694. Body: b.Bytes(),
  695. ContentType: "text/html",
  696. }
  697. h.PreRenderCache.Set(r.Context(), item)
  698. h.servePreRenderedItem(w, item)
  699. }
  700. func (h *Handler) resolvePackagePath(path string) string {
  701. var b strings.Builder
  702. b.WriteByte('/')
  703. appResources := strings.Trim(h.Resources.Package(), "/")
  704. b.WriteString(appResources)
  705. path = strings.Trim(path, "/")
  706. if b.Len() != 1 && path != "" {
  707. b.WriteByte('/')
  708. }
  709. b.WriteString(path)
  710. return b.String()
  711. }
  712. func (h *Handler) resolveStaticPath(path string) string {
  713. if isRemoteLocation(path) || !isStaticResourcePath(path) {
  714. return path
  715. }
  716. var b strings.Builder
  717. staticResources := strings.TrimSuffix(h.Resources.Static(), "/")
  718. b.WriteString(staticResources)
  719. path = strings.Trim(path, "/")
  720. b.WriteByte('/')
  721. b.WriteString(path)
  722. return b.String()
  723. }
  724. // Icon describes a square image that is used in various places such as
  725. // application icon, favicon or loading icon.
  726. type Icon struct {
  727. // The path or url to a square image/png file. It must have a side of 192px.
  728. //
  729. // Path is relative to the root directory.
  730. Default string
  731. // The path or url to larger square image/png file. It must have a side of
  732. // 512px.
  733. //
  734. // Path is relative to the root directory.
  735. Large string
  736. // The path or url to a square image/png file that is used for IOS/IPadOS
  737. // home screen icon. It must have a side of 192px.
  738. //
  739. // Path is relative to the root directory.
  740. //
  741. // DEFAULT: Icon.Default
  742. AppleTouch string
  743. Mask string
  744. MaskColor string
  745. }
  746. // Environment describes the environment variables to pass to the progressive
  747. // web app.
  748. type Environment map[string]string
  749. func normalizeFilePath(path string) string {
  750. if runtime.GOOS == "windows" {
  751. return strings.ReplaceAll(path, "/", `\`)
  752. }
  753. return path
  754. }
  755. func isRemoteLocation(path string) bool {
  756. return strings.HasPrefix(path, "https://") ||
  757. strings.HasPrefix(path, "http://")
  758. }
  759. func isStaticResourcePath(path string) bool {
  760. return strings.HasPrefix(path, "/web/") ||
  761. strings.HasPrefix(path, "web/")
  762. }
  763. type httpResource struct {
  764. Path string
  765. ContentType string
  766. Body []byte
  767. ExpireAt time.Time
  768. }
  769. func (r httpResource) Len() int {
  770. return len(r.Body)
  771. }
  772. func (r httpResource) IsExpired() bool {
  773. return r.ExpireAt != time.Time{} && r.ExpireAt.Before(time.Now())
  774. }