controller.go 14.3 KB
Newer Older
A
astaxie 已提交
1
// Beego (http://beego.me/)
A
astaxie 已提交
2

A
astaxie 已提交
3
// @description beego is an open-source, high-performance web framework for the Go programming language.
A
astaxie 已提交
4

A
astaxie 已提交
5
// @link        http://github.com/astaxie/beego for the canonical source repository
A
astaxie 已提交
6

A
astaxie 已提交
7
// @license     http://github.com/astaxie/beego/blob/master/LICENSE
A
astaxie 已提交
8

A
astaxie 已提交
9 10
// @authors     astaxie

A
#2  
astaxie 已提交
11 12 13 14
package beego

import (
	"bytes"
A
astaxie 已提交
15
	"errors"
A
#2  
astaxie 已提交
16
	"html/template"
A
astaxie 已提交
17
	"io"
A
#2  
astaxie 已提交
18
	"io/ioutil"
A
astaxie 已提交
19
	"mime/multipart"
A
#2  
astaxie 已提交
20 21
	"net/http"
	"net/url"
A
astaxie 已提交
22
	"os"
A
astaxie 已提交
23
	"reflect"
A
#2  
astaxie 已提交
24
	"strconv"
A
astaxie 已提交
25
	"strings"
A
astaxie 已提交
26 27 28

	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/session"
S
slene 已提交
29
	"github.com/astaxie/beego/utils"
A
#2  
astaxie 已提交
30 31
)

A
astaxie 已提交
32 33 34
//commonly used mime-types
const (
	applicationJson = "application/json"
35
	applicationXml  = "application/xml"
A
astaxie 已提交
36 37 38
	textXml         = "text/xml"
)

A
astaxie 已提交
39
var (
40
	// custom error when user stop request handler manually.
A
astaxie 已提交
41 42
	USERSTOPRUN                                            = errors.New("User stop run")
	GlobalControllerRouter map[string][]ControllerComments = make(map[string][]ControllerComments) //pkgpath+controller:comments
A
astaxie 已提交
43 44
)

A
astaxie 已提交
45 46
// store the comment for the controller method
type ControllerComments struct {
47 48 49 50
	Method           string
	Router           string
	AllowHTTPMethods []string
	Params           []map[string]string
A
astaxie 已提交
51 52
}

53 54
// Controller defines some basic http request handler operations, such as
// http context, template and view, session and xsrf.
A
#2  
astaxie 已提交
55
type Controller struct {
56 57 58 59 60 61
	Ctx            *context.Context
	Data           map[interface{}]interface{}
	controllerName string
	actionName     string
	TplNames       string
	Layout         string
62
	LayoutSections map[string]string // the key is the section name and the value is the template name
63 64 65 66 67 68
	TplExt         string
	_xsrf_token    string
	gotofunc       string
	CruSession     session.SessionStore
	XSRFExpire     int
	AppController  interface{}
A
astaxie 已提交
69
	EnableRender   bool
70
	EnableXSRF     bool
A
astaxie 已提交
71
	methodMapping  map[string]func() //method:routertree
A
#2  
astaxie 已提交
72 73
}

74
// ControllerInterface is an interface to uniform all controller handler.
A
#2  
astaxie 已提交
75
type ControllerInterface interface {
76
	Init(ct *context.Context, controllerName, actionName string, app interface{})
A
#2  
astaxie 已提交
77 78 79 80 81 82 83 84 85 86
	Prepare()
	Get()
	Post()
	Delete()
	Put()
	Head()
	Patch()
	Options()
	Finish()
	Render() error
87 88
	XsrfToken() string
	CheckXsrfCookie() bool
A
astaxie 已提交
89
	HandlerFunc(fn string) bool
A
astaxie 已提交
90
	URLMapping()
A
#2  
astaxie 已提交
91 92
}

93
// Init generates default values of controller operations.
94
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
A
#2  
astaxie 已提交
95 96
	c.Layout = ""
	c.TplNames = ""
97 98
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
99 100
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
101
	c.AppController = app
A
astaxie 已提交
102
	c.EnableRender = true
103
	c.EnableXSRF = true
104
	c.Data = ctx.Input.Data
A
astaxie 已提交
105
	c.methodMapping = make(map[string]func())
A
#2  
astaxie 已提交
106 107
}

108
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
109 110 111 112
func (c *Controller) Prepare() {

}

113
// Finish runs after request function execution.
A
#2  
astaxie 已提交
114
func (c *Controller) Finish() {
A
astaxie 已提交
115 116 117

}

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

123
// Post adds a request function to handle POST request.
A
#2  
astaxie 已提交
124 125 126 127
func (c *Controller) Post() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

128
// Delete adds a request function to handle DELETE request.
A
#2  
astaxie 已提交
129 130 131 132
func (c *Controller) Delete() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

133
// Put adds a request function to handle PUT request.
A
#2  
astaxie 已提交
134 135 136 137
func (c *Controller) Put() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

138
// Head adds a request function to handle HEAD request.
A
#2  
astaxie 已提交
139 140 141 142
func (c *Controller) Head() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

143
// Patch adds a request function to handle PATCH request.
A
#2  
astaxie 已提交
144 145 146 147
func (c *Controller) Patch() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

148
// Options adds a request function to handle OPTIONS request.
A
#2  
astaxie 已提交
149 150 151 152
func (c *Controller) Options() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

A
astaxie 已提交
153
// call function fn
A
astaxie 已提交
154
func (c *Controller) HandlerFunc(fnname string) bool {
A
astaxie 已提交
155
	if v, ok := c.methodMapping[fnname]; ok {
A
astaxie 已提交
156
		v()
A
astaxie 已提交
157
		return true
A
astaxie 已提交
158
	} else {
A
astaxie 已提交
159
		return false
A
astaxie 已提交
160 161 162 163 164 165 166
	}
}

// URLMapping register the internal Controller router.
func (c *Controller) URLMapping() {
}

A
astaxie 已提交
167 168
func (c *Controller) Mapping(method string, fn func()) {
	c.methodMapping[method] = fn
A
astaxie 已提交
169 170
}

171
// Render sends the response with rendered template bytes as text/html type.
A
#2  
astaxie 已提交
172
func (c *Controller) Render() error {
A
astaxie 已提交
173
	if !c.EnableRender {
174 175
		return nil
	}
A
astaxie 已提交
176 177 178 179 180
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
181 182
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(rb)
A
astaxie 已提交
183 184 185 186
	}
	return nil
}

187
// RenderString returns the rendered template string. Do not send out response.
A
astaxie 已提交
188 189 190 191 192
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

傅小黑 已提交
193
// RenderBytes returns the bytes of rendered template string. Do not send out response.
A
astaxie 已提交
194
func (c *Controller) RenderBytes() ([]byte, error) {
A
#2  
astaxie 已提交
195 196 197
	//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 == "" {
傅小黑 已提交
198
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
199
		}
200
		if RunMode == "dev" {
A
astaxie 已提交
201
			BuildTemplate(ViewsPath)
202
		}
A
#2  
astaxie 已提交
203
		newbytes := bytes.NewBufferString("")
A
astaxie 已提交
204
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
205
			panic("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
206
		}
A
astaxie 已提交
207
		err := BeeTemplates[c.TplNames].ExecuteTemplate(newbytes, c.TplNames, c.Data)
A
astaxie 已提交
208
		if err != nil {
A
astaxie 已提交
209
			Trace("template Execute err:", err)
210
			return nil, err
A
astaxie 已提交
211
		}
A
#2  
astaxie 已提交
212 213
		tplcontent, _ := ioutil.ReadAll(newbytes)
		c.Data["LayoutContent"] = template.HTML(string(tplcontent))
214 215 216

		if c.LayoutSections != nil {
			for sectionName, sectionTpl := range c.LayoutSections {
217
				if sectionTpl == "" {
218 219 220 221 222 223 224 225 226 227 228 229 230 231 232
					c.Data[sectionName] = ""
					continue
				}

				sectionBytes := bytes.NewBufferString("")
				err = BeeTemplates[sectionTpl].ExecuteTemplate(sectionBytes, sectionTpl, c.Data)
				if err != nil {
					Trace("template Execute err:", err)
					return nil, err
				}
				sectionContent, _ := ioutil.ReadAll(sectionBytes)
				c.Data[sectionName] = template.HTML(string(sectionContent))
			}
		}

A
astaxie 已提交
233
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
234
		err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
A
#2  
astaxie 已提交
235 236
		if err != nil {
			Trace("template Execute err:", err)
237
			return nil, err
A
#2  
astaxie 已提交
238
		}
A
astaxie 已提交
239 240
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
241 242
	} else {
		if c.TplNames == "" {
傅小黑 已提交
243
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
244
		}
245
		if RunMode == "dev" {
A
astaxie 已提交
246
			BuildTemplate(ViewsPath)
247
		}
A
astaxie 已提交
248
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
249
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
250
			panic("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
251
		}
A
astaxie 已提交
252
		err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
A
#2  
astaxie 已提交
253
		if err != nil {
A
astaxie 已提交
254
			Trace("template Execute err:", err)
255
			return nil, err
A
#2  
astaxie 已提交
256
		}
A
astaxie 已提交
257 258
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
259 260 261
	}
}

262
// Redirect sends the redirection response to url with status code.
A
#2  
astaxie 已提交
263 264 265 266
func (c *Controller) Redirect(url string, code int) {
	c.Ctx.Redirect(code, url)
}

267
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
A
fix #16  
astaxie 已提交
268
func (c *Controller) Abort(code string) {
269 270 271 272 273 274 275 276
	status, err := strconv.Atoi(code)
	if err == nil {
		c.Ctx.Abort(status, code)
	} else {
		c.Ctx.Abort(200, code)
	}
}

277 278 279 280 281
// CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.
func (c *Controller) CustomAbort(status int, body string) {
	c.Ctx.Abort(status, body)
}

282
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
283
func (c *Controller) StopRun() {
A
astaxie 已提交
284
	panic(USERSTOPRUN)
A
fix #16  
astaxie 已提交
285 286
}

287 288
// UrlFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
A
astaxie 已提交
289 290 291 292 293
func (c *Controller) UrlFor(endpoint string, values ...string) string {
	if len(endpoint) <= 0 {
		return ""
	}
	if endpoint[0] == '.' {
傅小黑 已提交
294
		return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
A
astaxie 已提交
295 296 297 298 299
	} else {
		return UrlFor(endpoint, values...)
	}
}

300
// ServeJson sends a json response with encoding charset.
A
astaxie 已提交
301
func (c *Controller) ServeJson(encoding ...bool) {
A
astaxie 已提交
302 303
	var hasIndent bool
	var hasencoding bool
304
	if RunMode == "prod" {
A
astaxie 已提交
305
		hasIndent = false
306
	} else {
A
astaxie 已提交
307
		hasIndent = true
308
	}
A
astaxie 已提交
309
	if len(encoding) > 0 && encoding[0] == true {
A
astaxie 已提交
310
		hasencoding = true
A
astaxie 已提交
311
	}
A
astaxie 已提交
312
	c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
A
#2  
astaxie 已提交
313 314
}

傅小黑 已提交
315
// ServeJsonp sends a jsonp response.
L
lw 已提交
316
func (c *Controller) ServeJsonp() {
A
astaxie 已提交
317
	var hasIndent bool
318
	if RunMode == "prod" {
A
astaxie 已提交
319
		hasIndent = false
320
	} else {
A
astaxie 已提交
321
		hasIndent = true
L
lw 已提交
322
	}
A
astaxie 已提交
323
	c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
L
lw 已提交
324 325
}

傅小黑 已提交
326
// ServeXml sends xml response.
A
#2  
astaxie 已提交
327
func (c *Controller) ServeXml() {
A
astaxie 已提交
328
	var hasIndent bool
329
	if RunMode == "prod" {
A
astaxie 已提交
330
		hasIndent = false
331
	} else {
A
astaxie 已提交
332
		hasIndent = true
333
	}
A
astaxie 已提交
334
	c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
A
#2  
astaxie 已提交
335 336
}

A
astaxie 已提交
337 338 339 340 341 342 343 344 345 346 347 348 349
// ServeFormatted serve Xml OR Json, depending on the value of the Accept header
func (c *Controller) ServeFormatted() {
	accept := c.Ctx.Input.Header("Accept")
	switch accept {
	case applicationJson:
		c.ServeJson()
	case applicationXml, textXml:
		c.ServeXml()
	default:
		c.ServeJson()
	}
}

350
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
351
func (c *Controller) Input() url.Values {
A
astaxie 已提交
352
	if c.Ctx.Request.Form == nil {
353 354
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
355 356
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
357

358
// ParseForm maps input data map to obj struct.
359 360 361 362
func (c *Controller) ParseForm(obj interface{}) error {
	return ParseForm(c.Input(), obj)
}

363
// GetString returns the input value by key string.
364
func (c *Controller) GetString(key string) string {
A
astaxie 已提交
365
	return c.Ctx.Input.Query(key)
366 367
}

368 369
// 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 已提交
370
func (c *Controller) GetStrings(key string) []string {
A
asta.xie 已提交
371 372
	f := c.Input()
	if f == nil {
Y
yecrane 已提交
373 374
		return []string{}
	}
A
asta.xie 已提交
375
	vs := f[key]
A
fix #87  
astaxie 已提交
376 377 378 379
	if len(vs) > 0 {
		return vs
	}
	return []string{}
Y
yecrane 已提交
380 381
}

382
// GetInt returns input value as int64.
383
func (c *Controller) GetInt(key string) (int64, error) {
A
astaxie 已提交
384
	return strconv.ParseInt(c.Ctx.Input.Query(key), 10, 64)
385 386
}

387
// GetBool returns input value as bool.
388
func (c *Controller) GetBool(key string) (bool, error) {
A
astaxie 已提交
389
	return strconv.ParseBool(c.Ctx.Input.Query(key))
390 391
}

392
// GetFloat returns input value as float64.
A
astaxie 已提交
393
func (c *Controller) GetFloat(key string) (float64, error) {
A
astaxie 已提交
394
	return strconv.ParseFloat(c.Ctx.Input.Query(key), 64)
A
astaxie 已提交
395 396
}

397 398
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
A
astaxie 已提交
399 400 401 402
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

403 404
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
A
astaxie 已提交
405 406 407 408 409 410
func (c *Controller) SaveToFile(fromfile, tofile string) error {
	file, _, err := c.Ctx.Request.FormFile(fromfile)
	if err != nil {
		return err
	}
	defer file.Close()
傅小黑 已提交
411
	f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
A
astaxie 已提交
412 413 414 415 416 417 418 419
	if err != nil {
		return err
	}
	defer f.Close()
	io.Copy(f, file)
	return nil
}

420
// StartSession starts session and load old session data info this controller.
A
astaxie 已提交
421 422
func (c *Controller) StartSession() session.SessionStore {
	if c.CruSession == nil {
423
		c.CruSession = c.Ctx.Input.CruSession
A
astaxie 已提交
424 425
	}
	return c.CruSession
X
xiemengjun 已提交
426
}
A
session  
astaxie 已提交
427

428
// SetSession puts value into session.
429
func (c *Controller) SetSession(name interface{}, value interface{}) {
A
astaxie 已提交
430 431 432 433
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Set(name, value)
A
session  
astaxie 已提交
434 435
}

436
// GetSession gets value from session.
437
func (c *Controller) GetSession(name interface{}) interface{} {
A
astaxie 已提交
438 439 440 441
	if c.CruSession == nil {
		c.StartSession()
	}
	return c.CruSession.Get(name)
A
session  
astaxie 已提交
442 443
}

444
// SetSession removes value from session.
445
func (c *Controller) DelSession(name interface{}) {
A
astaxie 已提交
446 447 448 449
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Delete(name)
A
session  
astaxie 已提交
450
}
A
fix #87  
astaxie 已提交
451

452 453
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
454
func (c *Controller) SessionRegenerateID() {
455 456 457
	if c.CruSession != nil {
		c.CruSession.SessionRelease(c.Ctx.ResponseWriter)
	}
458 459 460 461
	c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
	c.Ctx.Input.CruSession = c.CruSession
}

462
// DestroySession cleans session data and session cookie.
A
astaxie 已提交
463
func (c *Controller) DestroySession() {
464
	c.Ctx.Input.CruSession.Flush()
A
astaxie 已提交
465 466 467
	GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}

468
// IsAjax returns this request is ajax or not.
A
fix #87  
astaxie 已提交
469
func (c *Controller) IsAjax() bool {
A
astaxie 已提交
470
	return c.Ctx.Input.IsAjax()
A
fix #87  
astaxie 已提交
471
}
A
astaxie 已提交
472

473
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
474
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
475
	return c.Ctx.GetSecureCookie(Secret, key)
476 477
}

478
// SetSecureCookie puts value into cookie after encoded the value.
479 480
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
	c.Ctx.SetSecureCookie(Secret, name, value, others...)
481 482
}

483
// XsrfToken creates a xsrf token string and returns.
A
astaxie 已提交
484 485
func (c *Controller) XsrfToken() string {
	if c._xsrf_token == "" {
486 487
		token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
		if !ok {
A
astaxie 已提交
488
			var expire int64
A
astaxie 已提交
489
			if c.XSRFExpire > 0 {
A
astaxie 已提交
490
				expire = int64(c.XSRFExpire)
A
astaxie 已提交
491
			} else {
A
astaxie 已提交
492
				expire = int64(XSRFExpire)
A
astaxie 已提交
493
			}
494
			token = string(utils.RandomCreateBytes(32))
495
			c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
A
astaxie 已提交
496 497 498 499 500 501
		}
		c._xsrf_token = token
	}
	return c._xsrf_token
}

502 503 504
// 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 已提交
505
func (c *Controller) CheckXsrfCookie() bool {
506 507 508
	if !c.EnableXSRF {
		return true
	}
A
astaxie 已提交
509 510 511 512 513 514 515 516 517
	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 已提交
518
	} else if c._xsrf_token != token {
A
astaxie 已提交
519 520 521 522 523
		c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
	}
	return true
}

524
// XsrfFormHtml writes an input field contains xsrf token value.
A
astaxie 已提交
525 526
func (c *Controller) XsrfFormHtml() string {
	return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
傅小黑 已提交
527
		c._xsrf_token + "\"/>"
A
astaxie 已提交
528
}
A
fix #18  
astaxie 已提交
529

530
// GetControllerAndAction gets the executing controller name and action name.
531 532
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
	return c.controllerName, c.actionName
A
fix #18  
astaxie 已提交
533
}