controller.go 13.0 KB
Newer Older
A
#2  
astaxie 已提交
1 2 3 4
package beego

import (
	"bytes"
A
astaxie 已提交
5
	"crypto/hmac"
6
	"crypto/rand"
A
astaxie 已提交
7 8
	"crypto/sha1"
	"encoding/base64"
A
astaxie 已提交
9
	"errors"
A
astaxie 已提交
10
	"fmt"
A
#2  
astaxie 已提交
11
	"html/template"
A
astaxie 已提交
12
	"io"
A
#2  
astaxie 已提交
13
	"io/ioutil"
A
astaxie 已提交
14
	"mime/multipart"
A
#2  
astaxie 已提交
15 16
	"net/http"
	"net/url"
A
astaxie 已提交
17
	"os"
A
astaxie 已提交
18
	"reflect"
A
#2  
astaxie 已提交
19
	"strconv"
A
astaxie 已提交
20
	"strings"
A
astaxie 已提交
21
	"time"
A
astaxie 已提交
22 23 24

	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/session"
A
#2  
astaxie 已提交
25 26
)

A
astaxie 已提交
27
var (
28
	// custom error when user stop request handler manually.
A
astaxie 已提交
29 30 31
	USERSTOPRUN = errors.New("User stop run")
)

32 33
// Controller defines some basic http request handler operations, such as
// http context, template and view, session and xsrf.
A
#2  
astaxie 已提交
34
type Controller struct {
35 36 37 38 39 40 41 42 43 44 45 46
	Ctx            *context.Context
	Data           map[interface{}]interface{}
	controllerName string
	actionName     string
	TplNames       string
	Layout         string
	TplExt         string
	_xsrf_token    string
	gotofunc       string
	CruSession     session.SessionStore
	XSRFExpire     int
	AppController  interface{}
A
#2  
astaxie 已提交
47 48
}

49
// ControllerInterface is an interface to uniform all controller handler.
A
#2  
astaxie 已提交
50
type ControllerInterface interface {
51
	Init(ct *context.Context, controllerName, actionName string, app interface{})
A
#2  
astaxie 已提交
52 53 54 55 56 57 58 59 60 61
	Prepare()
	Get()
	Post()
	Delete()
	Put()
	Head()
	Patch()
	Options()
	Finish()
	Render() error
62 63
	XsrfToken() string
	CheckXsrfCookie() bool
A
#2  
astaxie 已提交
64 65
}

66
// Init generates default values of controller operations.
67
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
A
#2  
astaxie 已提交
68 69 70
	c.Data = make(map[interface{}]interface{})
	c.Layout = ""
	c.TplNames = ""
71 72
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
73 74
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
75
	c.AppController = app
A
#2  
astaxie 已提交
76 77
}

78
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
79 80 81 82
func (c *Controller) Prepare() {

}

83
// Finish runs after request function execution.
A
#2  
astaxie 已提交
84
func (c *Controller) Finish() {
A
astaxie 已提交
85 86 87

}

88
// Get adds a request function to handle GET request.
A
#2  
astaxie 已提交
89 90 91 92
func (c *Controller) Get() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

93
// Post adds a request function to handle POST request.
A
#2  
astaxie 已提交
94 95 96 97
func (c *Controller) Post() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

98
// Delete adds a request function to handle DELETE request.
A
#2  
astaxie 已提交
99 100 101 102
func (c *Controller) Delete() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

103
// Put adds a request function to handle PUT request.
A
#2  
astaxie 已提交
104 105 106 107
func (c *Controller) Put() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

108
// Head adds a request function to handle HEAD request.
A
#2  
astaxie 已提交
109 110 111 112
func (c *Controller) Head() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

113
// Patch adds a request function to handle PATCH request.
A
#2  
astaxie 已提交
114 115 116 117
func (c *Controller) Patch() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

118
// Options adds a request function to handle OPTIONS request.
A
#2  
astaxie 已提交
119 120 121 122
func (c *Controller) Options() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

123
// Render sends the response with rendered template bytes as text/html type.
A
#2  
astaxie 已提交
124
func (c *Controller) Render() error {
A
astaxie 已提交
125 126 127 128 129
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
130 131
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(rb)
A
astaxie 已提交
132 133 134 135
	}
	return nil
}

136
// RenderString returns the rendered template string. Do not send out response.
A
astaxie 已提交
137 138 139 140 141
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

142
// RenderBytes returns the bytes of renderd tempate string. Do not send out response.
A
astaxie 已提交
143
func (c *Controller) RenderBytes() ([]byte, error) {
A
#2  
astaxie 已提交
144 145 146
	//if the controller has set layout, then first get the tplname's content set the content to the layout
	if c.Layout != "" {
		if c.TplNames == "" {
傅小黑 已提交
147
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
148
		}
149
		if RunMode == "dev" {
A
astaxie 已提交
150
			BuildTemplate(ViewsPath)
151
		}
A
#2  
astaxie 已提交
152
		newbytes := bytes.NewBufferString("")
A
astaxie 已提交
153
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
154 155
			panic("can't find templatefile in the path:" + c.TplNames)
			return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
156
		}
A
astaxie 已提交
157
		err := BeeTemplates[c.TplNames].ExecuteTemplate(newbytes, c.TplNames, c.Data)
A
astaxie 已提交
158
		if err != nil {
A
astaxie 已提交
159
			Trace("template Execute err:", err)
160
			return nil, err
A
astaxie 已提交
161
		}
A
#2  
astaxie 已提交
162 163
		tplcontent, _ := ioutil.ReadAll(newbytes)
		c.Data["LayoutContent"] = template.HTML(string(tplcontent))
A
astaxie 已提交
164
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
165
		err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
A
#2  
astaxie 已提交
166 167
		if err != nil {
			Trace("template Execute err:", err)
168
			return nil, err
A
#2  
astaxie 已提交
169
		}
A
astaxie 已提交
170 171
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
172 173
	} else {
		if c.TplNames == "" {
傅小黑 已提交
174
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
175
		}
176
		if RunMode == "dev" {
A
astaxie 已提交
177
			BuildTemplate(ViewsPath)
178
		}
A
astaxie 已提交
179
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
180
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
181 182
			panic("can't find templatefile in the path:" + c.TplNames)
			return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
183
		}
A
astaxie 已提交
184
		err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
A
#2  
astaxie 已提交
185
		if err != nil {
A
astaxie 已提交
186
			Trace("template Execute err:", err)
187
			return nil, err
A
#2  
astaxie 已提交
188
		}
A
astaxie 已提交
189 190
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
191
	}
A
astaxie 已提交
192
	return []byte{}, nil
A
#2  
astaxie 已提交
193 194
}

195
// Redirect sends the redirection response to url with status code.
A
#2  
astaxie 已提交
196 197 198 199
func (c *Controller) Redirect(url string, code int) {
	c.Ctx.Redirect(code, url)
}

200
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
A
fix #16  
astaxie 已提交
201
func (c *Controller) Abort(code string) {
202 203 204 205 206 207 208 209
	status, err := strconv.Atoi(code)
	if err == nil {
		c.Ctx.Abort(status, code)
	} else {
		c.Ctx.Abort(200, code)
	}
}

210
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
211
func (c *Controller) StopRun() {
A
astaxie 已提交
212
	panic(USERSTOPRUN)
A
fix #16  
astaxie 已提交
213 214
}

215 216
// UrlFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
A
astaxie 已提交
217 218 219 220 221
func (c *Controller) UrlFor(endpoint string, values ...string) string {
	if len(endpoint) <= 0 {
		return ""
	}
	if endpoint[0] == '.' {
傅小黑 已提交
222
		return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
A
astaxie 已提交
223 224 225
	} else {
		return UrlFor(endpoint, values...)
	}
226
	return ""
A
astaxie 已提交
227 228
}

229
// ServeJson sends a json response with encoding charset.
A
astaxie 已提交
230
func (c *Controller) ServeJson(encoding ...bool) {
A
astaxie 已提交
231 232
	var hasIndent bool
	var hasencoding bool
233
	if RunMode == "prod" {
A
astaxie 已提交
234
		hasIndent = false
235
	} else {
A
astaxie 已提交
236
		hasIndent = true
237
	}
A
astaxie 已提交
238
	if len(encoding) > 0 && encoding[0] == true {
A
astaxie 已提交
239
		hasencoding = true
A
astaxie 已提交
240
	}
A
astaxie 已提交
241
	c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
A
#2  
astaxie 已提交
242 243
}

傅小黑 已提交
244
// ServeJsonp sends a jsonp response.
L
lw 已提交
245
func (c *Controller) ServeJsonp() {
A
astaxie 已提交
246
	var hasIndent bool
247
	if RunMode == "prod" {
A
astaxie 已提交
248
		hasIndent = false
249
	} else {
A
astaxie 已提交
250
		hasIndent = true
L
lw 已提交
251
	}
A
astaxie 已提交
252
	c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
L
lw 已提交
253 254
}

傅小黑 已提交
255
// ServeXml sends xml response.
A
#2  
astaxie 已提交
256
func (c *Controller) ServeXml() {
A
astaxie 已提交
257
	var hasIndent bool
258
	if RunMode == "prod" {
A
astaxie 已提交
259
		hasIndent = false
260
	} else {
A
astaxie 已提交
261
		hasIndent = true
262
	}
A
astaxie 已提交
263
	c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
A
#2  
astaxie 已提交
264 265
}

266
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
267
func (c *Controller) Input() url.Values {
268
	ct := c.Ctx.Request.Header.Get("Content-Type")
A
astaxie 已提交
269
	if strings.Contains(ct, "multipart/form-data") {
270 271 272 273
		c.Ctx.Request.ParseMultipartForm(MaxMemory) //64MB
	} else {
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
274 275
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
276

277
// ParseForm maps input data map to obj struct.
278 279 280 281
func (c *Controller) ParseForm(obj interface{}) error {
	return ParseForm(c.Input(), obj)
}

282
// GetString returns the input value by key string.
283 284 285 286
func (c *Controller) GetString(key string) string {
	return c.Input().Get(key)
}

287 288
// GetStrings returns the input string slice by key string.
// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
Y
yecrane 已提交
289
func (c *Controller) GetStrings(key string) []string {
A
fix #87  
astaxie 已提交
290 291
	r := c.Ctx.Request
	if r.Form == nil {
Y
yecrane 已提交
292 293
		return []string{}
	}
A
fix #87  
astaxie 已提交
294 295 296 297 298
	vs := r.Form[key]
	if len(vs) > 0 {
		return vs
	}
	return []string{}
Y
yecrane 已提交
299 300
}

301
// GetInt returns input value as int64.
302 303 304 305
func (c *Controller) GetInt(key string) (int64, error) {
	return strconv.ParseInt(c.Input().Get(key), 10, 64)
}

306
// GetBool returns input value as bool.
307 308 309 310
func (c *Controller) GetBool(key string) (bool, error) {
	return strconv.ParseBool(c.Input().Get(key))
}

311
// GetFloat returns input value as float64.
A
astaxie 已提交
312 313 314 315
func (c *Controller) GetFloat(key string) (float64, error) {
	return strconv.ParseFloat(c.Input().Get(key), 64)
}

316 317
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
A
astaxie 已提交
318 319 320 321
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

322 323
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
A
astaxie 已提交
324 325 326 327 328 329
func (c *Controller) SaveToFile(fromfile, tofile string) error {
	file, _, err := c.Ctx.Request.FormFile(fromfile)
	if err != nil {
		return err
	}
	defer file.Close()
傅小黑 已提交
330
	f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
A
astaxie 已提交
331 332 333 334 335 336 337 338
	if err != nil {
		return err
	}
	defer f.Close()
	io.Copy(f, file)
	return nil
}

339
// StartSession starts session and load old session data info this controller.
A
astaxie 已提交
340 341
func (c *Controller) StartSession() session.SessionStore {
	if c.CruSession == nil {
342
		c.CruSession = c.Ctx.Input.CruSession
A
astaxie 已提交
343 344
	}
	return c.CruSession
X
xiemengjun 已提交
345
}
A
session  
astaxie 已提交
346

347
// SetSession puts value into session.
348
func (c *Controller) SetSession(name interface{}, value interface{}) {
A
astaxie 已提交
349 350 351 352
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Set(name, value)
A
session  
astaxie 已提交
353 354
}

355
// GetSession gets value from session.
356
func (c *Controller) GetSession(name interface{}) interface{} {
A
astaxie 已提交
357 358 359 360
	if c.CruSession == nil {
		c.StartSession()
	}
	return c.CruSession.Get(name)
A
session  
astaxie 已提交
361 362
}

363
// SetSession removes value from session.
364
func (c *Controller) DelSession(name interface{}) {
A
astaxie 已提交
365 366 367 368
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Delete(name)
A
session  
astaxie 已提交
369
}
A
fix #87  
astaxie 已提交
370

371 372
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
373 374 375 376 377
func (c *Controller) SessionRegenerateID() {
	c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
	c.Ctx.Input.CruSession = c.CruSession
}

378
// DestroySession cleans session data and session cookie.
A
astaxie 已提交
379 380 381 382
func (c *Controller) DestroySession() {
	GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}

383
// IsAjax returns this request is ajax or not.
A
fix #87  
astaxie 已提交
384
func (c *Controller) IsAjax() bool {
A
astaxie 已提交
385
	return c.Ctx.Input.IsAjax()
A
fix #87  
astaxie 已提交
386
}
A
astaxie 已提交
387

388
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
389 390 391 392 393 394 395 396
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
	val := c.Ctx.GetCookie(key)
	if val == "" {
		return "", false
	}

	parts := strings.SplitN(val, "|", 3)

A
astaxie 已提交
397 398 399 400
	if len(parts) != 3 {
		return "", false
	}

401 402 403 404 405 406 407 408 409 410
	vs := parts[0]
	timestamp := parts[1]
	sig := parts[2]

	h := hmac.New(sha1.New, []byte(Secret))
	fmt.Fprintf(h, "%s%s", vs, timestamp)

	if fmt.Sprintf("%02x", h.Sum(nil)) != sig {
		return "", false
	}
A
astaxie 已提交
411
	res, _ := base64.URLEncoding.DecodeString(vs)
412 413 414
	return string(res), true
}

415
// SetSecureCookie puts value into cookie after encoded the value.
A
astaxie 已提交
416
func (c *Controller) SetSecureCookie(Secret, name, val string, age int64) {
417 418 419 420 421 422 423 424 425
	vs := base64.URLEncoding.EncodeToString([]byte(val))
	timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
	h := hmac.New(sha1.New, []byte(Secret))
	fmt.Fprintf(h, "%s%s", vs, timestamp)
	sig := fmt.Sprintf("%02x", h.Sum(nil))
	cookie := strings.Join([]string{vs, timestamp, sig}, "|")
	c.Ctx.SetCookie(name, cookie, age, "/")
}

426
// XsrfToken creates a xsrf token string and returns.
A
astaxie 已提交
427 428
func (c *Controller) XsrfToken() string {
	if c._xsrf_token == "" {
429 430
		token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
		if !ok {
A
astaxie 已提交
431
			var expire int64
A
astaxie 已提交
432
			if c.XSRFExpire > 0 {
A
astaxie 已提交
433
				expire = int64(c.XSRFExpire)
A
astaxie 已提交
434
			} else {
A
astaxie 已提交
435
				expire = int64(XSRFExpire)
A
astaxie 已提交
436
			}
437
			token = getRandomString(15)
438
			c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
A
astaxie 已提交
439 440 441 442 443 444
		}
		c._xsrf_token = token
	}
	return c._xsrf_token
}

445 446 447
// CheckXsrfCookie checks xsrf token in this request is valid or not.
// the token can provided in request header "X-Xsrftoken" and "X-CsrfToken"
// or in form field value named as "_xsrf".
A
astaxie 已提交
448 449 450 451 452 453 454 455 456 457
func (c *Controller) CheckXsrfCookie() bool {
	token := c.GetString("_xsrf")
	if token == "" {
		token = c.Ctx.Request.Header.Get("X-Xsrftoken")
	}
	if token == "" {
		token = c.Ctx.Request.Header.Get("X-Csrftoken")
	}
	if token == "" {
		c.Ctx.Abort(403, "'_xsrf' argument missing from POST")
A
astaxie 已提交
458
	} else if c._xsrf_token != token {
A
astaxie 已提交
459 460 461 462 463
		c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
	}
	return true
}

464
// XsrfFormHtml writes an input field contains xsrf token value.
A
astaxie 已提交
465 466
func (c *Controller) XsrfFormHtml() string {
	return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
傅小黑 已提交
467
		c._xsrf_token + "\"/>"
A
astaxie 已提交
468
}
A
fix #18  
astaxie 已提交
469

470
// GetControllerAndAction gets the executing controller name and action name.
471 472
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
	return c.controllerName, c.actionName
A
fix #18  
astaxie 已提交
473
}
474

475
// getRandomString returns random string.
476 477 478 479 480 481 482 483 484
func getRandomString(n int) string {
	const alphanum = "0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz"
	var bytes = make([]byte, n)
	rand.Read(bytes)
	for i, b := range bytes {
		bytes[i] = alphanum[b%byte(len(alphanum))]
	}
	return string(bytes)
}