-
Notifications
You must be signed in to change notification settings - Fork 0
/
render.go
45 lines (37 loc) · 1.02 KB
/
render.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
45
package looli
import (
"encoding/json"
"fmt"
"html/template"
"io"
"net/http"
)
var (
plainContentType = []string{"text/plain; charset=utf-8"}
jsonContentType = []string{"application/json; charset=utf-8"}
htmlContentType = []string{"text/html; charset=utf-8"}
)
func setContentType(rw http.ResponseWriter, value []string) {
header := rw.Header()
header["Content-Type"] = value
}
func renderString(rw http.ResponseWriter, format string, values ...interface{}) (err error) {
setContentType(rw, plainContentType)
if len(values) > 0 {
_, err = fmt.Fprintf(rw, format, values...)
} else {
_, err = io.WriteString(rw, format)
}
return
}
func renderJSON(rw http.ResponseWriter, data interface{}) error {
setContentType(rw, jsonContentType)
return json.NewEncoder(rw).Encode(data)
}
func renderHTML(rw http.ResponseWriter, templ *template.Template, name string, data interface{}) error {
setContentType(rw, htmlContentType)
if name == "" {
return templ.Execute(rw, data)
}
return templ.ExecuteTemplate(rw, name, data)
}