71 lines
1.9 KiB
Go
71 lines
1.9 KiB
Go
package render
|
|
|
|
import (
|
|
"context"
|
|
"net/http"
|
|
|
|
"github.com/a-h/templ"
|
|
templruntime "github.com/a-h/templ/runtime"
|
|
|
|
"git.ma-al.com/goc_marek/ps_shop/internal/assets"
|
|
"git.ma-al.com/goc_marek/ps_shop/internal/viewmodel"
|
|
"git.ma-al.com/goc_marek/ps_shop/templates"
|
|
)
|
|
|
|
func init() {
|
|
// Minimize templ's internal buffering so HTML reaches the client as it is rendered.
|
|
templruntime.DefaultBufferSize = 1
|
|
}
|
|
|
|
type Engine struct {
|
|
assets assets.Manifest
|
|
}
|
|
|
|
func New(manifest assets.Manifest) *Engine {
|
|
return &Engine{assets: manifest}
|
|
}
|
|
|
|
func (e *Engine) Product(w http.ResponseWriter, r *http.Request, data viewmodel.ProductPageData) error {
|
|
startHTMLStream(w)
|
|
component := templates.ProductPage(data, e.assets.CSSPath("app.css"), e.assets.JSPath("app.js"))
|
|
return streamComponent(r.Context(), w, component)
|
|
}
|
|
|
|
func (e *Engine) Category(w http.ResponseWriter, r *http.Request, data viewmodel.CategoryPageData) error {
|
|
startHTMLStream(w)
|
|
component := templates.CategoryPage(data, e.assets.CSSPath("app.css"), e.assets.JSPath("app.js"))
|
|
return streamComponent(r.Context(), w, component)
|
|
}
|
|
|
|
func (e *Engine) Cart(w http.ResponseWriter, r *http.Request, data viewmodel.CartPageData) error {
|
|
startHTMLStream(w)
|
|
component := templates.CartPage(data, e.assets.CSSPath("app.css"), e.assets.JSPath("app.js"))
|
|
return streamComponent(r.Context(), w, component)
|
|
}
|
|
|
|
func startHTMLStream(w http.ResponseWriter) {
|
|
if w == nil {
|
|
return
|
|
}
|
|
headers := w.Header()
|
|
if headers.Get("Content-Type") == "" {
|
|
headers.Set("Content-Type", "text/html; charset=utf-8")
|
|
}
|
|
w.WriteHeader(http.StatusOK)
|
|
if flusher, ok := w.(http.Flusher); ok {
|
|
flusher.Flush()
|
|
}
|
|
}
|
|
|
|
func streamComponent(ctx context.Context, w http.ResponseWriter, component templ.Component) error {
|
|
if component == nil {
|
|
return nil
|
|
}
|
|
var buffer templruntime.Buffer
|
|
buffer.Reset(w)
|
|
if err := component.Render(ctx, &buffer); err != nil {
|
|
return err
|
|
}
|
|
return buffer.Flush()
|
|
}
|