DEVELOPMENT ENVIRONMENT

~liljamo/emerwen-web

ref: 797037fe5da9b632166a17b9e7f57ec2ae0d35e3 emerwen-web/internal/renderer/renderer.go -rw-r--r-- 1.5 KiB
797037feJonni Liljamo feat: conform to new protocol changes a day ago
                                                                                
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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
/*
 * Copyright (C) 2024 Jonni Liljamo <jonni@liljamo.com>
 *
 * This file is licensed under GPL-3.0-or-later, see NOTICE and LICENSE for
 * more information.
 */

// Package renderer provides a gin HTMLRender implementation.
package renderer

import (
	"context"
	"net/http"

	"github.com/a-h/templ"
	"github.com/gin-gonic/gin/render"
)

// TemplRender is a gin HTMLRender implementation for templ rendering.
type TemplRender struct {
	Ctx       context.Context
	Status    int
	Component templ.Component
}

// New constructs a new TemplRender struct.
func New(ctx context.Context, status int, component templ.Component) *TemplRender {
	return &TemplRender{
		Ctx:       ctx,
		Status:    status,
		Component: component,
	}
}

// Instance returns a new TemplRender instance.
func (t *TemplRender) Instance( /* name */ _ string, component interface{}) render.Render {
	if templComponent, ok := component.(templ.Component); ok {
		return &TemplRender{
			Ctx:       context.Background(),
			Status:    -1,
			Component: templComponent,
		}
	}
	return nil
}

// Render executes a template and writes its result.
func (t TemplRender) Render(w http.ResponseWriter) error {
	t.WriteContentType(w)
	if t.Status != -1 {
		w.WriteHeader(t.Status)
	}
	if t.Component != nil {
		return t.Component.Render(t.Ctx, w)
	}
	return nil
}

// WriteContentType writes writes the content type.
func (t TemplRender) WriteContentType(w http.ResponseWriter) {
	w.Header().Set("Content-Type", "text/html; charset=utf-8")
}