-
Notifications
You must be signed in to change notification settings - Fork 15
/
Copy pathmiddleware.go
59 lines (51 loc) · 1.05 KB
/
middleware.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
package ginpongo2
import (
"github.com/flosch/pongo2"
. "github.com/gin-gonic/gin"
"net/http"
"fmt"
)
func Pongo2() HandlerFunc {
return func(c *Context) {
c.Next()
name := stringFromContext(c, "template")
data, _ := c.Get("data")
if name == "" {
return
}
template := pongo2.Must(pongo2.FromFile(name))
err := template.ExecuteWriter(convertContext(data), c.Writer)
if err != nil {
http.Error(c.Writer, err.Error(), http.StatusInternalServerError)
}
}
}
func stringFromContext(c *Context, input string) string {
raw, ok := c.Get(input)
if ok {
strVal, ok := raw.(string)
if ok {
return strVal
}
}
return ""
}
func convertContext(thing interface{}) pongo2.Context {
if thing != nil {
context, isMap := thing.(map[string]interface{})
if isMap {
return context
}
}
return nil
}
func getContext(templateData interface{}, err error) pongo2.Context {
if templateData == nil || err != nil {
return nil
}
contextData, isMap := templateData.(map[string]interface{})
if isMap {
return contextData
}
return nil
}