Skip to content

Commit

Permalink
Merge pull request #6 from netresearch/perf/prerender-index
Browse files Browse the repository at this point in the history
  • Loading branch information
TheDevMinerTV authored Jul 20, 2023
2 parents 73466fe + 3e90936 commit a14fd5b
Show file tree
Hide file tree
Showing 2 changed files with 35 additions and 10 deletions.
32 changes: 29 additions & 3 deletions internal/web/templates/templates.go
Original file line number Diff line number Diff line change
@@ -1,9 +1,15 @@
package templates

import "embed"
import (
"bytes"
_ "embed"
"html/template"

//go:embed *.html
var Templates embed.FS
"github.com/netresearch/ldap-selfservice-password-changer/internal/options"
)

//go:embed index.html
var rawIndex string

type InputOpts struct {
Name string
Expand All @@ -24,3 +30,23 @@ func MakeInputOpts(name, placeholder, type_, autocomplete string) InputOpts {
autocomplete,
}
}

func RenderIndex(opts *options.Opts) ([]byte, error) {
funcs := template.FuncMap{"InputOpts": MakeInputOpts}

tpl, err := template.New("index").Funcs(funcs).Parse(rawIndex)
if err != nil {
return nil, err
}

data := map[string]any{
"opts": opts,
}

var buf bytes.Buffer
if err = tpl.ExecuteTemplate(&buf, "index", data); err != nil {
return nil, err
}

return buf.Bytes(), nil
}
13 changes: 6 additions & 7 deletions main.go
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,6 @@ import (
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/compress"
"github.com/gofiber/fiber/v2/middleware/filesystem"
"github.com/gofiber/template/html/v2"
"github.com/netresearch/ldap-selfservice-password-changer/internal/options"
"github.com/netresearch/ldap-selfservice-password-changer/internal/rpc"
"github.com/netresearch/ldap-selfservice-password-changer/internal/web/static"
Expand All @@ -22,13 +21,14 @@ func main() {
log.Fatalf("An error occurred during initialization: %v", err)
}

views := html.NewFileSystem(http.FS(templates.Templates), ".html")
views.AddFunc("InputOpts", templates.MakeInputOpts)
index, err := templates.RenderIndex(opts)
if err != nil {
log.Fatalf("An error occurred during rendering the page: %v", err)
}

app := fiber.New(fiber.Config{
AppName: "netresearch/ldap-selfservice-password-changer",
BodyLimit: 4 * 1024,
Views: views,
})

app.Use(compress.New(compress.Config{
Expand All @@ -41,9 +41,8 @@ func main() {
}))

app.Get("/", func(c *fiber.Ctx) error {
return c.Render("index", fiber.Map{
"opts": opts,
})
c.Set("Content-Type", fiber.MIMETextHTMLCharsetUTF8)
return c.Send(index)
})

app.Post("/api/rpc", rpcHandler.Handle)
Expand Down

0 comments on commit a14fd5b

Please sign in to comment.