forked from codetainerapp/codetainer
-
Notifications
You must be signed in to change notification settings - Fork 0
/
http-helpers.go
116 lines (88 loc) · 2.49 KB
/
http-helpers.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
package codetainer
import (
"encoding/json"
"io/ioutil"
"net"
"net/http"
"text/template"
"github.com/dustin/go-humanize"
"github.com/gorilla/sessions"
"github.com/gorilla/websocket"
)
var upgrader = &websocket.Upgrader{ReadBufferSize: 1024, WriteBufferSize: 1024}
var funcs template.FuncMap = map[string]interface{}{
"DateFormat": DateFormat,
"PrettyNumber": func(number int64) string {
return humanize.Comma(number)
},
}
func jsonError(error_message error, w http.ResponseWriter) error {
w.WriteHeader(500)
Log.Error("Response error: ", error_message)
return renderJson(APIErrorResponse{
Error: true,
Message: error_message.Error(),
}, w)
}
func renderJson(data interface{}, w http.ResponseWriter) error {
js, err := json.Marshal(data)
if err != nil {
return err
}
w.Header().Set("Content-Type", "application/json")
w.Write(js)
return nil
}
func newTemplate(filename string, includeLayout bool) *template.Template {
var file []byte
var err error
var base []byte
var helpers []byte
if DevMode {
file, err = ioutil.ReadFile("web/" + filename)
base, err = ioutil.ReadFile("web/layout.html")
helpers, err = ioutil.ReadFile("web/helpers.html")
} else {
file, err = Asset("web/" + filename)
base, err = Asset("web/layout.html")
helpers, err = Asset("web/helpers.html")
}
if err != nil {
Log.Error(err)
}
var layout string
if includeLayout {
layout = string(base) + string(helpers) + string(file)
} else {
layout = string(helpers) + string(file)
}
return template.Must(template.New("*").Delims("<%", "%>").Funcs(funcs).Parse(layout))
}
type Context struct {
Session *sessions.Session
W http.ResponseWriter
R *http.Request
WS *websocket.Conn
}
func executeTemplate(ctx *Context, name string, status int, data interface{}) error {
ctx.W.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.W.WriteHeader(status)
return newTemplate(name, true).Execute(ctx.W, data)
}
func executeRaw(ctx *Context, name string, status int, data interface{}) error {
ctx.W.Header().Set("Content-Type", "text/html; charset=utf-8")
ctx.W.WriteHeader(status)
return newTemplate(name, false).Execute(ctx.W, data)
}
func GetRemoteAddr(req *http.Request) (string, error) {
if forwardedFor := req.Header.Get("X-FORWARDED-FOR"); forwardedFor != "" {
if ipParsed := net.ParseIP(forwardedFor); ipParsed != nil {
return ipParsed.String(), nil
}
}
ip, _, err := net.SplitHostPort(req.RemoteAddr)
if err != nil {
return "", err
}
return ip, nil
}