cookie ready

This commit is contained in:
2026-05-13 22:34:11 +02:00
parent 8c4e664ca8
commit 1b53c1c199
16 changed files with 798 additions and 146 deletions
+23 -2
View File
@@ -1,13 +1,22 @@
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
}
@@ -19,13 +28,13 @@ func New(manifest assets.Manifest) *Engine {
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 component.Render(r.Context(), w)
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 component.Render(r.Context(), w)
return streamComponent(r.Context(), w, component)
}
func startHTMLStream(w http.ResponseWriter) {
@@ -41,3 +50,15 @@ func startHTMLStream(w http.ResponseWriter) {
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()
}
+56
View File
@@ -0,0 +1,56 @@
package render
import (
"context"
"io"
"net/http"
"testing"
"github.com/a-h/templ"
)
type writeCountingResponseWriter struct {
header http.Header
writes int
body []byte
}
func (w *writeCountingResponseWriter) Header() http.Header {
if w.header == nil {
w.header = make(http.Header)
}
return w.header
}
func (w *writeCountingResponseWriter) Write(p []byte) (int, error) {
w.writes++
w.body = append(w.body, p...)
return len(p), nil
}
func (w *writeCountingResponseWriter) WriteHeader(statusCode int) {}
func (w *writeCountingResponseWriter) Flush() {}
func TestStreamComponentWritesIncrementally(t *testing.T) {
w := &writeCountingResponseWriter{}
component := templ.ComponentFunc(func(ctx context.Context, writer io.Writer) error {
if _, err := writer.Write([]byte("a")); err != nil {
return err
}
if _, err := writer.Write([]byte("b")); err != nil {
return err
}
return nil
})
if err := streamComponent(context.Background(), w, component); err != nil {
t.Fatalf("streamComponent() error = %v", err)
}
if got := string(w.body); got != "ab" {
t.Fatalf("body = %q, want %q", got, "ab")
}
if w.writes < 2 {
t.Fatalf("writes = %d, want at least 2 incremental writes", w.writes)
}
}