2022-01-04 20:23:25 +00:00
|
|
|
package renderer
|
|
|
|
|
|
|
|
import (
|
2022-05-16 06:15:09 +00:00
|
|
|
"encoding/json"
|
|
|
|
"encoding/xml"
|
2022-05-21 03:36:54 +00:00
|
|
|
"fmt"
|
2022-05-16 06:15:09 +00:00
|
|
|
"html/template"
|
|
|
|
"net/http"
|
2022-01-04 20:23:25 +00:00
|
|
|
)
|
|
|
|
|
2022-01-08 05:52:37 +00:00
|
|
|
func Template(t ...string) http.Handler {
|
2022-05-16 06:15:09 +00:00
|
|
|
tmpl := template.Must(template.ParseFiles(t...))
|
2022-01-04 20:23:25 +00:00
|
|
|
|
2022-05-16 06:15:09 +00:00
|
|
|
handlerFunc := func(w http.ResponseWriter, req *http.Request) {
|
2022-05-21 03:36:54 +00:00
|
|
|
err := tmpl.Execute(w, req)
|
|
|
|
if err != nil {
|
|
|
|
fmt.Printf(err.Error())
|
|
|
|
}
|
2022-05-16 06:15:09 +00:00
|
|
|
}
|
2022-01-04 20:23:25 +00:00
|
|
|
|
2022-05-16 06:15:09 +00:00
|
|
|
return http.HandlerFunc(handlerFunc)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|
|
|
|
|
2022-08-01 00:08:05 +00:00
|
|
|
func Subtree(path string) http.Handler {
|
|
|
|
return http.FileServer(http.Dir(path))
|
|
|
|
}
|
|
|
|
|
2022-01-04 20:23:25 +00:00
|
|
|
func JSON(key string) http.Handler {
|
2022-05-16 06:15:09 +00:00
|
|
|
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)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func XML(key string) http.Handler {
|
2022-05-16 06:15:09 +00:00
|
|
|
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)
|
2022-01-04 20:23:25 +00:00
|
|
|
}
|