Skip to content

Commit

Permalink
feat: html server and template wrapper
Browse files Browse the repository at this point in the history
  • Loading branch information
noxecane committed Apr 17, 2024
1 parent 14070b0 commit fdad410
Show file tree
Hide file tree
Showing 2 changed files with 83 additions and 0 deletions.
15 changes: 15 additions & 0 deletions html/files.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,15 @@
package html

import (
"net/http"

"github.com/go-chi/chi/v5"
)

// Server creates route for routing requests for static files
func Server(router *chi.Mux, folder string) {
fs := http.FileServer(http.Dir("./" + folder))
handler := http.StripPrefix("/"+folder+"/", fs)

router.Get("/"+folder+"/*", handler.ServeHTTP)
}
68 changes: 68 additions & 0 deletions html/template.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,68 @@
package html

import (
"bytes"
jsonslow "encoding/json"
"html/template"
"net/http"

"github.com/noxecane/anansi"
"github.com/noxecane/anansi/json"
"github.com/rs/zerolog"
)

type Template interface {
Render(*http.Request, http.ResponseWriter, any) error
}

type htmlTemplate struct {
name string
tmpl *template.Template
}

func Parse(name string, source ...string) Template {
var tmpl *template.Template
if len(source) == 1 {
tmpl = template.Must(template.New(name).ParseFiles(source...))
} else if len(source) > 0 {
tmpl = template.Must(template.ParseFiles(source...))
} else {
panic("souce can't be empty")
}

return &htmlTemplate{name, tmpl}
}

func (t *htmlTemplate) Render(r *http.Request, w http.ResponseWriter, data any) error {
log := zerolog.Ctx(r.Context())
raw, err := json.Marshal(data)

if data != nil {
log.UpdateContext(func(ctx zerolog.Context) zerolog.Context {
buffer := new(bytes.Buffer)
if err != nil {
panic(err)
}

if err := jsonslow.Compact(buffer, raw); err != nil {
panic(err)
}

return ctx.RawJSON("html_data", buffer.Bytes())
})
}

err = t.tmpl.ExecuteTemplate(w, t.name, data)

if err == nil {
log.Info().
Interface("response_headers", anansi.SimpleHeaders(w.Header())).
Msg("")
} else {
log.Err(err).
Interface("response_headers", anansi.SimpleHeaders(w.Header())).
Msg("")
}

return err
}

0 comments on commit fdad410

Please sign in to comment.