controller.go 14.1 KB
Newer Older
A
astaxie 已提交
1 2 3 4 5 6
// Beego (http://beego.me/)
// @description beego is an open-source, high-performance web framework for the Go programming language.
// @link        http://github.com/astaxie/beego for the canonical source repository
// @license     http://github.com/astaxie/beego/blob/master/LICENSE
// @authors     astaxie

A
#2  
astaxie 已提交
7 8 9 10
package beego

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

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

A
astaxie 已提交
28 29 30
//commonly used mime-types
const (
	applicationJson = "application/json"
31
	applicationXml  = "application/xml"
A
astaxie 已提交
32 33 34
	textXml         = "text/xml"
)

A
astaxie 已提交
35
var (
36
	// custom error when user stop request handler manually.
A
astaxie 已提交
37 38
	USERSTOPRUN            = errors.New("User stop run")
	GlobalControllerRouter map[string]map[string]*Tree //pkgpath+controller:method:routertree
A
astaxie 已提交
39 40
)

41 42
// Controller defines some basic http request handler operations, such as
// http context, template and view, session and xsrf.
A
#2  
astaxie 已提交
43
type Controller struct {
44 45 46 47 48 49
	Ctx            *context.Context
	Data           map[interface{}]interface{}
	controllerName string
	actionName     string
	TplNames       string
	Layout         string
50
	LayoutSections map[string]string // the key is the section name and the value is the template name
51 52 53 54 55 56
	TplExt         string
	_xsrf_token    string
	gotofunc       string
	CruSession     session.SessionStore
	XSRFExpire     int
	AppController  interface{}
A
astaxie 已提交
57
	EnableRender   bool
58
	EnableXSRF     bool
A
astaxie 已提交
59
	Routers        map[string]*Tree //method:routertree
A
#2  
astaxie 已提交
60 61
}

62
// ControllerInterface is an interface to uniform all controller handler.
A
#2  
astaxie 已提交
63
type ControllerInterface interface {
64
	Init(ct *context.Context, controllerName, actionName string, app interface{})
A
#2  
astaxie 已提交
65 66 67 68 69 70 71 72 73 74
	Prepare()
	Get()
	Post()
	Delete()
	Put()
	Head()
	Patch()
	Options()
	Finish()
	Render() error
75 76
	XsrfToken() string
	CheckXsrfCookie() bool
A
astaxie 已提交
77 78
	HandlerFunc(fn interface{})
	URLMapping()
A
#2  
astaxie 已提交
79 80
}

81
// Init generates default values of controller operations.
82
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
A
#2  
astaxie 已提交
83 84
	c.Layout = ""
	c.TplNames = ""
85 86
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
87 88
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
89
	c.AppController = app
A
astaxie 已提交
90
	c.EnableRender = true
91
	c.EnableXSRF = true
92
	c.Data = ctx.Input.Data
A
astaxie 已提交
93
	c.Routers = make(map[string]*Tree)
A
#2  
astaxie 已提交
94 95
}

96
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
97 98 99 100
func (c *Controller) Prepare() {

}

101
// Finish runs after request function execution.
A
#2  
astaxie 已提交
102
func (c *Controller) Finish() {
A
astaxie 已提交
103 104 105

}

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

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

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

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

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

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

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

A
astaxie 已提交
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
// call function fn
func (c *Controller) HandlerFunc(fn interface{}) {
	if v, ok := fn.(func()); ok {
		v()
	}
}

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

func (c *Controller) Mapping(method, pattern string, fn func()) {
	method = strings.ToLower(method)
	if !utils.InSlice(method, HTTPMETHOD) && method != "*" {
		Critical("add mapping method:" + method + " is a valid method")
		return
	}
	if t, ok := c.Routers[method]; ok {
		t.AddRouter(pattern, fn)
	} else {
		t = NewTree()
		t.AddRouter(pattern, fn)
		c.Routers[method] = t
	}
}

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

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

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

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

		if c.LayoutSections != nil {
			for sectionName, sectionTpl := range c.LayoutSections {
213
				if sectionTpl == "" {
214 215 216 217 218 219 220 221 222 223 224 225 226 227 228
					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 已提交
229
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
230
		err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
A
#2  
astaxie 已提交
231 232
		if err != nil {
			Trace("template Execute err:", err)
233
			return nil, err
A
#2  
astaxie 已提交
234
		}
A
astaxie 已提交
235 236
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
237 238
	} else {
		if c.TplNames == "" {
傅小黑 已提交
239
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
240
		}
241
		if RunMode == "dev" {
A
astaxie 已提交
242
			BuildTemplate(ViewsPath)
243
		}
A
astaxie 已提交
244
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
245
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
246
			panic("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
247
		}
A
astaxie 已提交
248
		err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
A
#2  
astaxie 已提交
249
		if err != nil {
A
astaxie 已提交
250
			Trace("template Execute err:", err)
251
			return nil, err
A
#2  
astaxie 已提交
252
		}
A
astaxie 已提交
253 254
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
255 256 257
	}
}

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

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

273
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
274
func (c *Controller) StopRun() {
A
astaxie 已提交
275
	panic(USERSTOPRUN)
A
fix #16  
astaxie 已提交
276 277
}

278 279
// UrlFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
A
astaxie 已提交
280 281 282 283 284
func (c *Controller) UrlFor(endpoint string, values ...string) string {
	if len(endpoint) <= 0 {
		return ""
	}
	if endpoint[0] == '.' {
傅小黑 已提交
285
		return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
A
astaxie 已提交
286 287 288 289 290
	} else {
		return UrlFor(endpoint, values...)
	}
}

291
// ServeJson sends a json response with encoding charset.
A
astaxie 已提交
292
func (c *Controller) ServeJson(encoding ...bool) {
A
astaxie 已提交
293 294
	var hasIndent bool
	var hasencoding bool
295
	if RunMode == "prod" {
A
astaxie 已提交
296
		hasIndent = false
297
	} else {
A
astaxie 已提交
298
		hasIndent = true
299
	}
A
astaxie 已提交
300
	if len(encoding) > 0 && encoding[0] == true {
A
astaxie 已提交
301
		hasencoding = true
A
astaxie 已提交
302
	}
A
astaxie 已提交
303
	c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
A
#2  
astaxie 已提交
304 305
}

傅小黑 已提交
306
// ServeJsonp sends a jsonp response.
L
lw 已提交
307
func (c *Controller) ServeJsonp() {
A
astaxie 已提交
308
	var hasIndent bool
309
	if RunMode == "prod" {
A
astaxie 已提交
310
		hasIndent = false
311
	} else {
A
astaxie 已提交
312
		hasIndent = true
L
lw 已提交
313
	}
A
astaxie 已提交
314
	c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
L
lw 已提交
315 316
}

傅小黑 已提交
317
// ServeXml sends xml response.
A
#2  
astaxie 已提交
318
func (c *Controller) ServeXml() {
A
astaxie 已提交
319
	var hasIndent bool
320
	if RunMode == "prod" {
A
astaxie 已提交
321
		hasIndent = false
322
	} else {
A
astaxie 已提交
323
		hasIndent = true
324
	}
A
astaxie 已提交
325
	c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
A
#2  
astaxie 已提交
326 327
}

A
astaxie 已提交
328 329 330 331 332 333 334 335 336 337 338 339 340
// 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()
	}
}

341
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
342
func (c *Controller) Input() url.Values {
A
astaxie 已提交
343
	if c.Ctx.Request.Form == nil {
344 345
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
346 347
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
348

349
// ParseForm maps input data map to obj struct.
350 351 352 353
func (c *Controller) ParseForm(obj interface{}) error {
	return ParseForm(c.Input(), obj)
}

354
// GetString returns the input value by key string.
355
func (c *Controller) GetString(key string) string {
A
astaxie 已提交
356
	return c.Ctx.Input.Query(key)
357 358
}

359 360
// 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 已提交
361
func (c *Controller) GetStrings(key string) []string {
A
asta.xie 已提交
362 363
	f := c.Input()
	if f == nil {
Y
yecrane 已提交
364 365
		return []string{}
	}
A
asta.xie 已提交
366
	vs := f[key]
A
fix #87  
astaxie 已提交
367 368 369 370
	if len(vs) > 0 {
		return vs
	}
	return []string{}
Y
yecrane 已提交
371 372
}

373
// GetInt returns input value as int64.
374
func (c *Controller) GetInt(key string) (int64, error) {
A
astaxie 已提交
375
	return strconv.ParseInt(c.Ctx.Input.Query(key), 10, 64)
376 377
}

378
// GetBool returns input value as bool.
379
func (c *Controller) GetBool(key string) (bool, error) {
A
astaxie 已提交
380
	return strconv.ParseBool(c.Ctx.Input.Query(key))
381 382
}

383
// GetFloat returns input value as float64.
A
astaxie 已提交
384
func (c *Controller) GetFloat(key string) (float64, error) {
A
astaxie 已提交
385
	return strconv.ParseFloat(c.Ctx.Input.Query(key), 64)
A
astaxie 已提交
386 387
}

388 389
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
A
astaxie 已提交
390 391 392 393
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

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

411
// StartSession starts session and load old session data info this controller.
A
astaxie 已提交
412 413
func (c *Controller) StartSession() session.SessionStore {
	if c.CruSession == nil {
414
		c.CruSession = c.Ctx.Input.CruSession
A
astaxie 已提交
415 416
	}
	return c.CruSession
X
xiemengjun 已提交
417
}
A
session  
astaxie 已提交
418

419
// SetSession puts value into session.
420
func (c *Controller) SetSession(name interface{}, value interface{}) {
A
astaxie 已提交
421 422 423 424
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Set(name, value)
A
session  
astaxie 已提交
425 426
}

427
// GetSession gets value from session.
428
func (c *Controller) GetSession(name interface{}) interface{} {
A
astaxie 已提交
429 430 431 432
	if c.CruSession == nil {
		c.StartSession()
	}
	return c.CruSession.Get(name)
A
session  
astaxie 已提交
433 434
}

435
// SetSession removes value from session.
436
func (c *Controller) DelSession(name interface{}) {
A
astaxie 已提交
437 438 439 440
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Delete(name)
A
session  
astaxie 已提交
441
}
A
fix #87  
astaxie 已提交
442

443 444
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
445
func (c *Controller) SessionRegenerateID() {
446 447 448
	if c.CruSession != nil {
		c.CruSession.SessionRelease(c.Ctx.ResponseWriter)
	}
449 450 451 452
	c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
	c.Ctx.Input.CruSession = c.CruSession
}

453
// DestroySession cleans session data and session cookie.
A
astaxie 已提交
454
func (c *Controller) DestroySession() {
455
	c.Ctx.Input.CruSession.Flush()
A
astaxie 已提交
456 457 458
	GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}

459
// IsAjax returns this request is ajax or not.
A
fix #87  
astaxie 已提交
460
func (c *Controller) IsAjax() bool {
A
astaxie 已提交
461
	return c.Ctx.Input.IsAjax()
A
fix #87  
astaxie 已提交
462
}
A
astaxie 已提交
463

464
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
465
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
466
	return c.Ctx.GetSecureCookie(Secret, key)
467 468
}

469
// SetSecureCookie puts value into cookie after encoded the value.
470 471
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
	c.Ctx.SetSecureCookie(Secret, name, value, others...)
472 473
}

474
// XsrfToken creates a xsrf token string and returns.
A
astaxie 已提交
475 476
func (c *Controller) XsrfToken() string {
	if c._xsrf_token == "" {
477 478
		token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
		if !ok {
A
astaxie 已提交
479
			var expire int64
A
astaxie 已提交
480
			if c.XSRFExpire > 0 {
A
astaxie 已提交
481
				expire = int64(c.XSRFExpire)
A
astaxie 已提交
482
			} else {
A
astaxie 已提交
483
				expire = int64(XSRFExpire)
A
astaxie 已提交
484
			}
485
			token = string(utils.RandomCreateBytes(32))
486
			c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
A
astaxie 已提交
487 488 489 490 491 492
		}
		c._xsrf_token = token
	}
	return c._xsrf_token
}

493 494 495
// 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 已提交
496
func (c *Controller) CheckXsrfCookie() bool {
497 498 499
	if !c.EnableXSRF {
		return true
	}
A
astaxie 已提交
500 501 502 503 504 505 506 507 508
	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 已提交
509
	} else if c._xsrf_token != token {
A
astaxie 已提交
510 511 512 513 514
		c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
	}
	return true
}

515
// XsrfFormHtml writes an input field contains xsrf token value.
A
astaxie 已提交
516 517
func (c *Controller) XsrfFormHtml() string {
	return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
傅小黑 已提交
518
		c._xsrf_token + "\"/>"
A
astaxie 已提交
519
}
A
fix #18  
astaxie 已提交
520

521
// GetControllerAndAction gets the executing controller name and action name.
522 523
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
	return c.controllerName, c.actionName
A
fix #18  
astaxie 已提交
524
}