go-sample-webpage/layoutmiddleware.go

46 lines
851 B
Go
Raw Normal View History

2021-11-03 01:10:36 +00:00
package main
import (
"bytes"
"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: webserver,
},
})
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()
render.HTML(w, http.StatusOK, "sub", template.HTML(string(content)))
})
}