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][]ControllerComments = make(map[string][]ControllerComments) //pkgpath+controller:comments
A
astaxie 已提交
39 40
)

A
astaxie 已提交
41 42 43 44 45
// store the comment for the controller method
type ControllerComments struct {
	method           string
	router           string
	allowHTTPMethods []string
A
astaxie 已提交
46
	params           []map[string]string
A
astaxie 已提交
47 48
}

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

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

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

104
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
105 106 107 108
func (c *Controller) Prepare() {

}

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

}

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

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

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

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

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

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

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

A
astaxie 已提交
149
// call function fn
A
astaxie 已提交
150 151
func (c *Controller) HandlerFunc(fnname string) {
	if v, ok := c.methodMapping[fnname]; ok {
A
astaxie 已提交
152
		v()
A
astaxie 已提交
153 154
	} else {
		Error("call funcname not exist in the methodMapping: " + fnname)
A
astaxie 已提交
155 156 157 158 159 160 161
	}
}

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

A
astaxie 已提交
162 163
func (c *Controller) Mapping(method string, fn func()) {
	c.methodMapping[method] = fn
A
astaxie 已提交
164 165
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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