@@ -0,0 +1,78 @@
1+package scrap_paper
2+
3+// We are building a service that uses htmx to return html from a url
4+import (
5+ "bytes"
6+ _ "embed"
7+ "fmt"
8+ "net/http"
9+
10+ "html/template"
11+
12+ "encore.dev"
13+)
14+
15+//go:embed index.html
16+var indexRawTemplate string
17+
18+type IndexTemplateData struct {
19+ Title string
20+ Env string
21+}
22+
23+func IndexHtml(data IndexTemplateData) (string, error) {
24+ tmpl := template.Must(template.New("index").Parse(indexRawTemplate))
25+
26+ var buf bytes.Buffer
27+ if err := tmpl.Execute(&buf, data); err != nil {
28+ return "", err
29+ }
30+ return buf.String(), nil
31+}
32+
33+//
34+// Warning: This is a fallback handler, being missused as a catch-all handler.
35+// It is used to handle requests that don't match any other route.
36+// In our case it means it renders the index page.
37+//
38+
39+//encore:api public raw path=/!fallback
40+func Index(w http.ResponseWriter, r *http.Request) {
41+ req := encore.CurrentRequest()
42+ env := encore.Meta().Environment.Name
43+ title := "📝 Scrap Paper - Home"
44+
45+ if env != "prod" {
46+ title = fmt.Sprintf("%s [%s]", title, env)
47+ }
48+
49+ if req.Path == "/" {
50+ html, err := IndexHtml(IndexTemplateData{
51+ Title: title,
52+ Env: env,
53+ })
54+ if err != nil {
55+ http.Error(w, err.Error(), http.StatusInternalServerError)
56+ return // TODO: Return an error page
57+ }
58+ w.Write([]byte(html))
59+
60+ return // DONE
61+ }
62+
63+ // Since we are abusing fallback handler to mount a page on "/"
64+ // we need to return a 404 error if the path is not "/"
65+ // TODO: Return an error page
66+ http.NotFound(w, r)
67+}
68+
69+//
70+// Handle static assets
71+//
72+
73+//encore:api public raw path=/assets/:filename
74+func Assets(w http.ResponseWriter, r *http.Request) {
75+ // This path is relative to the root of the project
76+ path := "." + encore.CurrentRequest().Path
77+ http.ServeFile(w, r, path)
78+}