summaryrefslogtreecommitdiff
path: root/render.go
blob: ee58b6457008cca59d6fb7960d8678875236c6dc (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package mux

import (
	"context"
	"io"
	"log/slog"
	"net/http"
)

type Renderer interface {
	Render(context.Context, http.ResponseWriter) error
}

func Render(w http.ResponseWriter, r *http.Request, renderable Renderer) {
	if err := renderable.Render(r.Context(), w); err != nil {
		slog.ErrorContext(r.Context(), "failed render template", slog.Any("err", err))
	}
}

type RendererFunc func(context.Context, http.ResponseWriter) error

func (r RendererFunc) Render(ctx context.Context, w http.ResponseWriter) error {
	return r(ctx, w)
}

type IoRenderer interface {
	Render(context.Context, io.Writer) error
}

func Http(code int, inner IoRenderer) Renderer {
	return httpWrapper{
		code:  code,
		inner: inner,
	}
}

type httpWrapper struct {
	code  int
	inner IoRenderer
}

func (r httpWrapper) Render(ctx context.Context, w http.ResponseWriter) error {
	w.WriteHeader(r.code)
	return r.inner.Render(ctx, w)
}