forked from martini-contrib/web
-
Notifications
You must be signed in to change notification settings - Fork 0
/
web.go
211 lines (183 loc) · 5.84 KB
/
web.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
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
// Package web provides a web.go compitable layer for reusing the code written with
// hoisie's `web.go` framework. Basiclly this package add web.Context to
// martini's dependency injection system.
package web
import (
"bytes"
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
"fmt"
"github.com/go-martini/martini"
"io/ioutil"
"mime"
"net/http"
"strconv"
"strings"
"time"
)
// A Context object is created for every incoming HTTP request, and is
// passed to handlers as an optional first argument. It provides information
// about the request, including the http.Request object, the GET and POST params,
// and acts as a Writer for the response.
type Context struct {
Request *http.Request
Params map[string]string
cookieSecret string
http.ResponseWriter
}
// if cookie secret is set to "", then SetSecureCookie would not work
func ContextWithCookieSecret(secret string) martini.Handler {
return func(w http.ResponseWriter, req *http.Request, mc martini.Context) {
ctx := &Context{req, map[string]string{}, secret, w}
//set some default headers
tm := time.Now().UTC()
//ignore errors from ParseForm because it's usually harmless.
req.ParseForm()
if len(req.Form) > 0 {
for k, v := range req.Form {
ctx.Params[k] = v[0]
}
}
ctx.SetHeader("Date", webTime(tm), true)
//Set the default content-type
ctx.SetHeader("Content-Type", "text/html; charset=utf-8", true)
// set martini context for web.Context
mc.Map(ctx)
}
}
// internal utility methods
func webTime(t time.Time) string {
ftime := t.Format(time.RFC1123)
if strings.HasSuffix(ftime, "UTC") {
ftime = ftime[0:len(ftime)-3] + "GMT"
}
return ftime
}
// WriteString writes string data into the response object.
func (ctx *Context) WriteString(content string) {
ctx.ResponseWriter.Write([]byte(content))
}
// Abort is a helper method that sends an HTTP header and an optional
// body. It is useful for returning 4xx or 5xx errors.
// Once it has been called, any return value from the handler will
// not be written to the response.
func (ctx *Context) Abort(status int, body string) {
ctx.ResponseWriter.WriteHeader(status)
ctx.ResponseWriter.Write([]byte(body))
}
// Redirect is a helper method for 3xx redirects.
func (ctx *Context) Redirect(status int, url_ string) {
ctx.ResponseWriter.Header().Set("Location", url_)
ctx.ResponseWriter.WriteHeader(status)
ctx.ResponseWriter.Write([]byte("Redirecting to: " + url_))
}
// Notmodified writes a 304 HTTP response
func (ctx *Context) NotModified() {
ctx.ResponseWriter.WriteHeader(304)
}
// NotFound writes a 404 HTTP response
func (ctx *Context) NotFound(message string) {
ctx.ResponseWriter.WriteHeader(404)
ctx.ResponseWriter.Write([]byte(message))
}
//Unauthorized writes a 401 HTTP response
func (ctx *Context) Unauthorized() {
ctx.ResponseWriter.WriteHeader(401)
}
//Forbidden writes a 403 HTTP response
func (ctx *Context) Forbidden() {
ctx.ResponseWriter.WriteHeader(403)
}
// ContentType sets the Content-Type header for an HTTP response.
// For example, ctx.ContentType("json") sets the content-type to "application/json"
// If the supplied value contains a slash (/) it is set as the Content-Type
// verbatim. The return value is the content type as it was
// set, or an empty string if none was found.
func (ctx *Context) ContentType(val string) string {
var ctype string
if strings.ContainsRune(val, '/') {
ctype = val
} else {
if !strings.HasPrefix(val, ".") {
val = "." + val
}
ctype = mime.TypeByExtension(val)
}
if ctype != "" {
ctx.Header().Set("Content-Type", ctype)
}
return ctype
}
// SetHeader sets a response header. If `unique` is true, the current value
// of that header will be overwritten . If false, it will be appended.
func (ctx *Context) SetHeader(hdr string, val string, unique bool) {
if unique {
ctx.Header().Set(hdr, val)
} else {
ctx.Header().Add(hdr, val)
}
}
// SetCookie adds a cookie header to the response.
func (ctx *Context) SetCookie(cookie *http.Cookie) {
ctx.SetHeader("Set-Cookie", cookie.String(), false)
}
func getCookieSig(key string, val []byte, timestamp string) string {
hm := hmac.New(sha1.New, []byte(key))
hm.Write(val)
hm.Write([]byte(timestamp))
hex := fmt.Sprintf("%02x", hm.Sum(nil))
return hex
}
// NewCookie is a helper method that returns a new http.Cookie object.
// Duration is specified in seconds. If the duration is zero, the cookie is permanent.
// This can be used in conjunction with ctx.SetCookie.
func NewCookie(name string, value string, age int64) *http.Cookie {
var utctime time.Time
if age == 0 {
// 2^31 - 1 seconds (roughly 2038)
utctime = time.Unix(2147483647, 0)
} else {
utctime = time.Unix(time.Now().Unix()+age, 0)
}
return &http.Cookie{Name: name, Value: value, Expires: utctime}
}
func (ctx *Context) SetSecureCookie(name string, val string, age int64) {
//base64 encode the val
if len(ctx.cookieSecret) == 0 {
return
}
var buf bytes.Buffer
encoder := base64.NewEncoder(base64.StdEncoding, &buf)
encoder.Write([]byte(val))
encoder.Close()
vs := buf.String()
vb := buf.Bytes()
timestamp := strconv.FormatInt(time.Now().Unix(), 10)
sig := getCookieSig(ctx.cookieSecret, vb, timestamp)
cookie := strings.Join([]string{vs, timestamp, sig}, "|")
ctx.SetCookie(NewCookie(name, cookie, age))
}
func (ctx *Context) GetSecureCookie(name string) (string, bool) {
for _, cookie := range ctx.Request.Cookies() {
if cookie.Name != name {
continue
}
parts := strings.SplitN(cookie.Value, "|", 3)
val := parts[0]
timestamp := parts[1]
sig := parts[2]
if getCookieSig(ctx.cookieSecret, []byte(val), timestamp) != sig {
return "", false
}
ts, _ := strconv.ParseInt(timestamp, 0, 64)
if time.Now().Unix()-31*86400 > ts {
return "", false
}
buf := bytes.NewBufferString(val)
encoder := base64.NewDecoder(base64.StdEncoding, buf)
res, _ := ioutil.ReadAll(encoder)
return string(res), true
}
return "", false
}