quartzgun/renderer/renderer.go

57 lines
1.1 KiB
Go
Raw Normal View History

package renderer
import (
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"net/http"
)
func Template(t ...string) http.Handler {
tmpl := template.Must(template.ParseFiles(t...))
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
err := tmpl.Execute(w, req)
if err != nil {
fmt.Printf(err.Error())
}
}
return http.HandlerFunc(handlerFunc)
}
func Subtree(path string) http.Handler {
return http.FileServer(http.Dir(path))
}
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)
}