go-sample-webpage/pkg/webpage/layoutmiddleware.go

46 lines
861 B
Go
Raw Normal View History

2021-11-08 02:33:36 +00:00
package webpage
2021-11-03 01:10:36 +00:00
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{
2021-11-08 02:33:36 +00:00
FS: config.Templates,
2021-11-03 01:10:36 +00:00
},
})
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)))
})
}