quartzgun/renderer/renderer.go
Iris Lightshard 756a0739fd
initial commit
router with static files and dynamic handlers, renderers for templates, json, and xml, and beginnings of auth and cookie management
2022-01-04 13:23:25 -07:00

48 lines
1 KiB
Go

package renderer
import (
"net/http"
"html/template"
"encoding/json"
"encoding/xml"
)
func Template(t string) http.Handler {
tmpl := template.Must(template.ParseFiles(t))
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
tmpl.Execute(w, req)
}
return http.HandlerFunc(handlerFunc)
}
func JSON(key string) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
apiData := req.Context().Value(key)
data, err := json.Marshal(apiData)
if err != nil {
panic(err.Error())
}
w.Header().Set("Content-Type", "application/json")
w.Write(data)
}
return http.HandlerFunc(handlerFunc)
}
func XML(key string) http.Handler {
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
apiData := req.Context().Value(key)
data, err := xml.MarshalIndent(apiData, "", " ")
if err != nil {
panic(err.Error())
}
w.Header().Set("Content-Type", "application/xml")
w.Write(data)
}
return http.HandlerFunc(handlerFunc)
}