-
Notifications
You must be signed in to change notification settings - Fork 1
/
Copy pathviewer_html.go
44 lines (38 loc) · 1.23 KB
/
viewer_html.go
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
package xun
import (
"net/http"
)
// HtmlViewer is a viewer that renders a html template.
//
// It uses the `HtmlTemplate` type to render a template.
// The template is loaded from the file system when the viewer is created.
// The `Render` method renders the template with the given data and writes the
// result to the http.ResponseWriter.
type HtmlViewer struct {
template *HtmlTemplate
}
var htmlViewerMime = &MimeType{Type: "text", SubType: "html"}
// MimeType returns the MIME type of the HTML content.
//
// This implementation returns "text/html".
func (*HtmlViewer) MimeType() *MimeType {
return htmlViewerMime
}
// Render renders the template with the given data and writes the result to the http.ResponseWriter.
//
// This implementation uses the `HtmlTemplate.Execute` method to render the template.
// The rendered result is written to the http.ResponseWriter.
func (v *HtmlViewer) Render(w http.ResponseWriter, r *http.Request, data any) error { // skipcq: RVV-B0012
var err error
w.Header().Set("Content-Type", "text/html; charset=utf-8")
if r.Method != http.MethodHead {
buf := BufPool.Get()
defer BufPool.Put(buf)
err = v.template.Execute(buf, data)
if err != nil {
return err
}
_, err = buf.WriteTo(w)
}
return err
}