all repos — quartzgun @ 1dd23fe176ca430b11b550729d8cc06035afb609

lightweight web framework in go

renderer/renderer.go (raw)

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
46
47
48
package renderer

import (
	"encoding/json"
	"encoding/xml"
	"html/template"
	"net/http"
)

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)
}