controller.go 12.8 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
var (
29
	// custom error when user stop request handler manually.
A
astaxie 已提交
30 31 32
	USERSTOPRUN = errors.New("User stop run")
)

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

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

69
// Init generates default values of controller operations.
70
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
A
#2  
astaxie 已提交
71 72
	c.Layout = ""
	c.TplNames = ""
73 74
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
75 76
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
77
	c.AppController = app
78
	c.EnableReander = true
79
	c.Data = ctx.Input.Data
A
#2  
astaxie 已提交
80 81
}

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

}

87
// Finish runs after request function execution.
A
#2  
astaxie 已提交
88
func (c *Controller) Finish() {
A
astaxie 已提交
89 90 91

}

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

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

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

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

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

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

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

127
// Render sends the response with rendered template bytes as text/html type.
A
#2  
astaxie 已提交
128
func (c *Controller) Render() error {
129 130 131
	if !c.EnableReander {
		return nil
	}
A
astaxie 已提交
132 133 134 135 136
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
137 138
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(rb)
A
astaxie 已提交
139 140 141 142
	}
	return nil
}

143
// RenderString returns the rendered template string. Do not send out response.
A
astaxie 已提交
144 145 146 147 148
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

傅小黑 已提交
149
// RenderBytes returns the bytes of rendered template string. Do not send out response.
A
astaxie 已提交
150
func (c *Controller) RenderBytes() ([]byte, error) {
A
#2  
astaxie 已提交
151 152 153
	//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 == "" {
傅小黑 已提交
154
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
155
		}
156
		if RunMode == "dev" {
A
astaxie 已提交
157
			BuildTemplate(ViewsPath)
158
		}
A
#2  
astaxie 已提交
159
		newbytes := bytes.NewBufferString("")
A
astaxie 已提交
160
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
161
			panic("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
162
		}
A
astaxie 已提交
163
		err := BeeTemplates[c.TplNames].ExecuteTemplate(newbytes, c.TplNames, c.Data)
A
astaxie 已提交
164
		if err != nil {
A
astaxie 已提交
165
			Trace("template Execute err:", err)
166
			return nil, err
A
astaxie 已提交
167
		}
A
#2  
astaxie 已提交
168 169
		tplcontent, _ := ioutil.ReadAll(newbytes)
		c.Data["LayoutContent"] = template.HTML(string(tplcontent))
170 171 172

		if c.LayoutSections != nil {
			for sectionName, sectionTpl := range c.LayoutSections {
173
				if sectionTpl == "" {
174 175 176 177 178 179 180 181 182 183 184 185 186 187 188
					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 已提交
189
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
190
		err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
A
#2  
astaxie 已提交
191 192
		if err != nil {
			Trace("template Execute err:", err)
193
			return nil, err
A
#2  
astaxie 已提交
194
		}
A
astaxie 已提交
195 196
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
197 198
	} else {
		if c.TplNames == "" {
傅小黑 已提交
199
			c.TplNames = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
A
#2  
astaxie 已提交
200
		}
201
		if RunMode == "dev" {
A
astaxie 已提交
202
			BuildTemplate(ViewsPath)
203
		}
A
astaxie 已提交
204
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
205
		if _, ok := BeeTemplates[c.TplNames]; !ok {
傅小黑 已提交
206
			panic("can't find templatefile in the path:" + c.TplNames)
A
astaxie 已提交
207
		}
A
astaxie 已提交
208
		err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
A
#2  
astaxie 已提交
209
		if err != nil {
A
astaxie 已提交
210
			Trace("template Execute err:", err)
211
			return nil, err
A
#2  
astaxie 已提交
212
		}
A
astaxie 已提交
213 214
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
215 216 217
	}
}

218
// Redirect sends the redirection response to url with status code.
A
#2  
astaxie 已提交
219 220 221 222
func (c *Controller) Redirect(url string, code int) {
	c.Ctx.Redirect(code, url)
}

223
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
A
fix #16  
astaxie 已提交
224
func (c *Controller) Abort(code string) {
225 226 227 228 229 230 231 232
	status, err := strconv.Atoi(code)
	if err == nil {
		c.Ctx.Abort(status, code)
	} else {
		c.Ctx.Abort(200, code)
	}
}

233
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
234
func (c *Controller) StopRun() {
A
astaxie 已提交
235
	panic(USERSTOPRUN)
A
fix #16  
astaxie 已提交
236 237
}

238 239
// UrlFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
A
astaxie 已提交
240 241 242 243 244
func (c *Controller) UrlFor(endpoint string, values ...string) string {
	if len(endpoint) <= 0 {
		return ""
	}
	if endpoint[0] == '.' {
傅小黑 已提交
245
		return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
A
astaxie 已提交
246 247 248 249 250
	} else {
		return UrlFor(endpoint, values...)
	}
}

251
// ServeJson sends a json response with encoding charset.
A
astaxie 已提交
252
func (c *Controller) ServeJson(encoding ...bool) {
A
astaxie 已提交
253 254
	var hasIndent bool
	var hasencoding bool
255
	if RunMode == "prod" {
A
astaxie 已提交
256
		hasIndent = false
257
	} else {
A
astaxie 已提交
258
		hasIndent = true
259
	}
A
astaxie 已提交
260
	if len(encoding) > 0 && encoding[0] == true {
A
astaxie 已提交
261
		hasencoding = true
A
astaxie 已提交
262
	}
A
astaxie 已提交
263
	c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
A
#2  
astaxie 已提交
264 265
}

傅小黑 已提交
266
// ServeJsonp sends a jsonp response.
L
lw 已提交
267
func (c *Controller) ServeJsonp() {
A
astaxie 已提交
268
	var hasIndent bool
269
	if RunMode == "prod" {
A
astaxie 已提交
270
		hasIndent = false
271
	} else {
A
astaxie 已提交
272
		hasIndent = true
L
lw 已提交
273
	}
A
astaxie 已提交
274
	c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
L
lw 已提交
275 276
}

傅小黑 已提交
277
// ServeXml sends xml response.
A
#2  
astaxie 已提交
278
func (c *Controller) ServeXml() {
A
astaxie 已提交
279
	var hasIndent bool
280
	if RunMode == "prod" {
A
astaxie 已提交
281
		hasIndent = false
282
	} else {
A
astaxie 已提交
283
		hasIndent = true
284
	}
A
astaxie 已提交
285
	c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
A
#2  
astaxie 已提交
286 287
}

288
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
289
func (c *Controller) Input() url.Values {
A
astaxie 已提交
290
	if c.Ctx.Request.Form == nil {
291 292
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
293 294
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
295

296
// ParseForm maps input data map to obj struct.
297 298 299 300
func (c *Controller) ParseForm(obj interface{}) error {
	return ParseForm(c.Input(), obj)
}

301
// GetString returns the input value by key string.
302
func (c *Controller) GetString(key string) string {
A
astaxie 已提交
303
	return c.Ctx.Input.Query(key)
304 305
}

306 307
// 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 已提交
308
func (c *Controller) GetStrings(key string) []string {
A
asta.xie 已提交
309 310
	f := c.Input()
	if f == nil {
Y
yecrane 已提交
311 312
		return []string{}
	}
A
asta.xie 已提交
313
	vs := f[key]
A
fix #87  
astaxie 已提交
314 315 316 317
	if len(vs) > 0 {
		return vs
	}
	return []string{}
Y
yecrane 已提交
318 319
}

320
// GetInt returns input value as int64.
321
func (c *Controller) GetInt(key string) (int64, error) {
A
astaxie 已提交
322
	return strconv.ParseInt(c.Ctx.Input.Query(key), 10, 64)
323 324
}

325
// GetBool returns input value as bool.
326
func (c *Controller) GetBool(key string) (bool, error) {
A
astaxie 已提交
327
	return strconv.ParseBool(c.Ctx.Input.Query(key))
328 329
}

330
// GetFloat returns input value as float64.
A
astaxie 已提交
331
func (c *Controller) GetFloat(key string) (float64, error) {
A
astaxie 已提交
332
	return strconv.ParseFloat(c.Ctx.Input.Query(key), 64)
A
astaxie 已提交
333 334
}

335 336
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
A
astaxie 已提交
337 338 339 340
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

341 342
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
A
astaxie 已提交
343 344 345 346 347 348
func (c *Controller) SaveToFile(fromfile, tofile string) error {
	file, _, err := c.Ctx.Request.FormFile(fromfile)
	if err != nil {
		return err
	}
	defer file.Close()
傅小黑 已提交
349
	f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
A
astaxie 已提交
350 351 352 353 354 355 356 357
	if err != nil {
		return err
	}
	defer f.Close()
	io.Copy(f, file)
	return nil
}

358
// StartSession starts session and load old session data info this controller.
A
astaxie 已提交
359 360
func (c *Controller) StartSession() session.SessionStore {
	if c.CruSession == nil {
361
		c.CruSession = c.Ctx.Input.CruSession
A
astaxie 已提交
362 363
	}
	return c.CruSession
X
xiemengjun 已提交
364
}
A
session  
astaxie 已提交
365

366
// SetSession puts value into session.
367
func (c *Controller) SetSession(name interface{}, value interface{}) {
A
astaxie 已提交
368 369 370 371
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Set(name, value)
A
session  
astaxie 已提交
372 373
}

374
// GetSession gets value from session.
375
func (c *Controller) GetSession(name interface{}) interface{} {
A
astaxie 已提交
376 377 378 379
	if c.CruSession == nil {
		c.StartSession()
	}
	return c.CruSession.Get(name)
A
session  
astaxie 已提交
380 381
}

382
// SetSession removes value from session.
383
func (c *Controller) DelSession(name interface{}) {
A
astaxie 已提交
384 385 386 387
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Delete(name)
A
session  
astaxie 已提交
388
}
A
fix #87  
astaxie 已提交
389

390 391
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
392
func (c *Controller) SessionRegenerateID() {
393 394 395
	if c.CruSession != nil {
		c.CruSession.SessionRelease(c.Ctx.ResponseWriter)
	}
396 397 398 399
	c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
	c.Ctx.Input.CruSession = c.CruSession
}

400
// DestroySession cleans session data and session cookie.
A
astaxie 已提交
401
func (c *Controller) DestroySession() {
402
	c.Ctx.Input.CruSession.Flush()
A
astaxie 已提交
403 404 405
	GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}

406
// IsAjax returns this request is ajax or not.
A
fix #87  
astaxie 已提交
407
func (c *Controller) IsAjax() bool {
A
astaxie 已提交
408
	return c.Ctx.Input.IsAjax()
A
fix #87  
astaxie 已提交
409
}
A
astaxie 已提交
410

411
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
412
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
413
	return c.Ctx.GetSecureCookie(Secret, key)
414 415
}

416
// SetSecureCookie puts value into cookie after encoded the value.
417 418
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
	c.Ctx.SetSecureCookie(Secret, name, value, others...)
419 420
}

421
// XsrfToken creates a xsrf token string and returns.
A
astaxie 已提交
422 423
func (c *Controller) XsrfToken() string {
	if c._xsrf_token == "" {
424 425
		token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
		if !ok {
A
astaxie 已提交
426
			var expire int64
A
astaxie 已提交
427
			if c.XSRFExpire > 0 {
A
astaxie 已提交
428
				expire = int64(c.XSRFExpire)
A
astaxie 已提交
429
			} else {
A
astaxie 已提交
430
				expire = int64(XSRFExpire)
A
astaxie 已提交
431
			}
S
slene 已提交
432
			token = string(utils.RandomCreateBytes(15))
433
			c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
A
astaxie 已提交
434 435 436 437 438 439
		}
		c._xsrf_token = token
	}
	return c._xsrf_token
}

440 441 442
// 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 已提交
443 444 445 446 447 448 449 450 451 452
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 已提交
453
	} else if c._xsrf_token != token {
A
astaxie 已提交
454 455 456 457 458
		c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
	}
	return true
}

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

465
// GetControllerAndAction gets the executing controller name and action name.
466 467
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
	return c.controllerName, c.actionName
A
fix #18  
astaxie 已提交
468
}