Skip to main content

đŸ’ģ Html

The Html response takes a status code, a file path and data for the template language.

func Html(code int, file string, template interface{}) HttpResponse {

It will load the file, parse the template and write the result using the Bytes response.

E. g. you have this index.html file given:

Hello {{.user}}

then a possible response could look like this:

return Html(StatusOK, "./index.html", map[string]string{
"user": "Username",
})

The template will be parsed accodingly and produce the result

Hello Username
func Html(code int, file string, template any) Response {
content, err := parseTemplate(file, template)
if err != nil {
return Error(status.InternalServerError, fmt.Errorf("html: parseTemplate: %v", err))
}
return htmlResponse{code: code, data: []byte(*content)}
}

type htmlResponse struct {
code int
data []byte
}

func (h htmlResponse) ServeHTTP(rw http.ResponseWriter, r *http.Request) {
rw.WriteHeader(h.code)
rw.Header().Set(header.ContentType, ContentTypeTextHtml)
_, err := rw.Write(h.data)
if err != nil {
log.Printf("htmlResponse: ServeHttp write failed: %v", err)
}
}

func parseTemplate(templateFileName string, data any) (*string, error) {
t, err := template.ParseFiles(templateFileName)
if err != nil {
return nil, err
}
buf := new(bytes.Buffer)
if err = t.Execute(buf, data); err != nil {
return nil, err
}
body := buf.String()
return &body, nil
}