go-sample-webpage/pkg/webpage/layoutmiddleware.go
kekskurse 360ee1c5fe
Some checks failed
continuous-integration/drone/push Build is failing
stuff
2021-11-25 01:32:48 +01:00

56 lines
No EOL
1.1 KiB
Go

package webpage
import (
"bytes"
"github.com/go-chi/jwtauth/v5"
"github.com/unrolled/render"
"html/template"
"io"
"net/http"
)
type LayoutMiddlewareResponseWriter struct {
http.ResponseWriter
buf *bytes.Buffer
}
func (myrw *LayoutMiddlewareResponseWriter) Write(p []byte) (int, error) {
return myrw.buf.Write(p)
}
func TemplateMiddelware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
render := render.New(render.Options{
Layout: "layout",
FileSystem: &render.EmbedFileSystem{
FS: config.Templates,
},
})
rw := &LayoutMiddlewareResponseWriter{
ResponseWriter: w,
buf: &bytes.Buffer{},
}
next.ServeHTTP(rw, r)
content, err := io.ReadAll(rw.buf)
if err != nil {
panic(err)
}
rw.buf.Reset()
_, claims, _ := jwtauth.FromContext(r.Context())
loggedin := false
if claims["username"] != nil {
loggedin = true
}
render.HTML(w, http.StatusOK, "sub", map[string]interface{}{"loggedin": loggedin, "content": template.HTML(string(content))})
})
}