-
Notifications
You must be signed in to change notification settings - Fork 0
/
renderer.go
134 lines (109 loc) · 3.56 KB
/
renderer.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
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
package httpwaymid
import (
"encoding/json"
"fmt"
"html/template"
"io/ioutil"
"net/http"
"os"
"path/filepath"
"github.com/corneldamian/httpway"
)
//a simple JSON renderer
//from your handler you need to set on context your data (and optional the http status code)
//you need to set here what are those keys where you are going to save them
//data from ctx key "ctxDataVar" must be and object that can be marshal by json.Marshal
//data from ctx key "ctxHttpStatusCodeVar" must be int
func JSONRenderer(ctxDataVar, ctxHttpStatusCodeVar string) httpway.Handler {
return func(w http.ResponseWriter, r *http.Request) {
ctx := httpway.GetContext(r)
ctx.Next(w, r)
if ctx.Has(ctxDataVar) {
if ctx.StatusCode() != 0 {
ctx.Log().Error("I have json from context to write but the status already set")
return
}
w.Header().Set("Content-Type", "application/json")
data, err := json.Marshal(ctx.Get(ctxDataVar))
if err != nil {
ctx.Log().Error("I was unable to marshal to json: %s", err)
w.Write([]byte("{\"Error\": \"Internal server error\"}"))
w.WriteHeader(http.StatusInternalServerError)
return
}
if ctx.Has(ctxHttpStatusCodeVar) {
w.WriteHeader(ctx.Get(ctxHttpStatusCodeVar).(int))
}
n, err := w.Write(data)
if err != nil {
ctx.Log().Error("I was unable to write payload to the socket: %s", err)
return
}
if n != len(data) {
ctx.Log().Error("Not all data was written to the socket expected: %d sent %d (fix this with some retry's)", len(data), n)
}
}
}
}
// a simple golang Template Renderer
// this will scan the templeteDir and load all the files that ends in tmpl
// in handler you must set "ctxTemplateNameVar" wich is the template file name and
// "ctxTempalteDataVar" the data to pass to the template
// you can set a diffrent (the 200) http status code with "ctxHttpStatusCodeVar"
func TemplateRenderer(templateDir, ctxTemplateNameVar, ctxTempalteDataVar, ctxHttpStatusCodeVar string) httpway.Handler {
templates := template.Must(parseFiles(templateDir, getAllTemplatesFiles(templateDir)...))
return func(w http.ResponseWriter, r *http.Request) {
ctx := httpway.GetContext(r)
ctx.Next(w, r)
if ctx.Has(ctxTempalteDataVar) && ctx.Has(ctxTemplateNameVar) {
if ctx.Has(ctxHttpStatusCodeVar) {
w.WriteHeader(ctx.Get(ctxHttpStatusCodeVar).(int))
}
err := templates.ExecuteTemplate(w, ctx.Get(ctxTemplateNameVar).(string), ctx.Get(ctxTempalteDataVar))
if err != nil {
ctx.Log().Error("I was unable to execute template %s with error: %s", ctx.Get(ctxTemplateNameVar), err)
}
}
}
}
func getAllTemplatesFiles(templateDirName string) []string {
templatePages := make([]string, 0)
filepath.Walk(templateDirName, func(path string, info os.FileInfo, err error) error {
if !info.IsDir() {
templatePages = append(templatePages, path)
}
return nil
})
return templatePages
}
func parseFiles(templateDir string, filenames ...string) (*template.Template, error) {
if len(filenames) == 0 {
return nil, fmt.Errorf("template: no files named in call to ParseFiles")
}
if templateDir[len(templateDir)-1] != '/' {
templateDir = filepath.Clean(templateDir) + "/"
}
var t *template.Template
for _, filename := range filenames {
b, err := ioutil.ReadFile(filename)
if err != nil {
return nil, err
}
s := string(b)
name := filename[len(templateDir):]
var tmpl *template.Template
if t == nil {
t = template.New(name)
}
if name == t.Name() {
tmpl = t
} else {
tmpl = t.New(name)
}
_, err = tmpl.Parse(s)
if err != nil {
return nil, err
}
}
return t, nil
}