You can not select more than 25 topics
Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
40 lines
1.0 KiB
40 lines
1.0 KiB
3 years ago
|
package routes
|
||
3 years ago
|
|
||
|
import (
|
||
|
"io"
|
||
|
|
||
|
routing "github.com/jackwhelpton/fasthttp-routing/v2"
|
||
|
"github.com/valyala/fasthttp"
|
||
3 years ago
|
|
||
|
"code.tokarch.uk/mainnika/nikita-tokarch-uk/pkg/templates"
|
||
3 years ago
|
)
|
||
|
|
||
|
var _ routing.DataWriter = (*TemplateWriter)(nil)
|
||
|
|
||
|
// staticWriter is thread-safe static instance of template writer
|
||
|
var staticWriter = &TemplateWriter{}
|
||
|
|
||
|
// TemplateWriter is the fasthttp data writer that loads and executes template using the content
|
||
|
type TemplateWriter struct{}
|
||
|
|
||
|
// SetHeader sets the content type to HTML since all templates are HTML
|
||
|
func (tw *TemplateWriter) SetHeader(rh *fasthttp.ResponseHeader) {
|
||
|
rh.SetContentType(routing.MIME_HTML)
|
||
|
}
|
||
|
|
||
|
// Write executes the template and writes result to the response writer
|
||
|
func (tw *TemplateWriter) Write(w io.Writer, content interface{}) error {
|
||
|
|
||
|
template := templates.GetTemplateOf(content)
|
||
|
|
||
|
return template.Execute(w, content)
|
||
|
}
|
||
|
|
||
|
// useTemplateWriter is the routing middleware to set the default data writer
|
||
3 years ago
|
func (r *Routes) useTemplateWriter(c *routing.Context) (err error) {
|
||
3 years ago
|
|
||
|
c.SetDataWriter(staticWriter)
|
||
|
|
||
|
return
|
||
|
}
|