controller.go 13.3 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 31 32 33 34
//commonly used mime-types
const (
	applicationJson = "application/json"
	applicationXml  = "applicatoin/xml"
	textXml         = "text/xml"
)

A
astaxie 已提交
35
var (
36
	// custom error when user stop request handler manually.
A
astaxie 已提交
37 38 39
	USERSTOPRUN = errors.New("User stop run")
)

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

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

77
// Init generates default values of controller operations.
78
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
A
#2  
astaxie 已提交
79 80
	c.Layout = ""
	c.TplNames = ""
81 82
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
83 84
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
85
	c.AppController = app
A
astaxie 已提交
86
	c.EnableRender = true
87
	c.EnableXSRF = true
88
	c.Data = ctx.Input.Data
A
#2  
astaxie 已提交
89 90
}

91
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
92 93 94 95
func (c *Controller) Prepare() {

}

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

}

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

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

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

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

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

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

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

136
// Render sends the response with rendered template bytes as text/html type.
A
#2  
astaxie 已提交
137
func (c *Controller) Render() error {
A
astaxie 已提交
138
	if !c.EnableRender {
139 140
		return nil
	}
A
astaxie 已提交
141 142 143 144 145
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
146 147
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(rb)
A
astaxie 已提交
148 149 150 151
	}
	return nil
}

152
// RenderString returns the rendered template string. Do not send out response.
A
astaxie 已提交
153 154 155 156 157
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

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

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

227
// Redirect sends the redirection response to url with status code.
A
#2  
astaxie 已提交
228 229 230 231
func (c *Controller) Redirect(url string, code int) {
	c.Ctx.Redirect(code, url)
}

232
// Aborts stops controller handler and show the error data if code is defined in ErrorMap or code string.
A
fix #16  
astaxie 已提交
233
func (c *Controller) Abort(code string) {
234 235 236 237 238 239 240 241
	status, err := strconv.Atoi(code)
	if err == nil {
		c.Ctx.Abort(status, code)
	} else {
		c.Ctx.Abort(200, code)
	}
}

242
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
243
func (c *Controller) StopRun() {
A
astaxie 已提交
244
	panic(USERSTOPRUN)
A
fix #16  
astaxie 已提交
245 246
}

247 248
// UrlFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
A
astaxie 已提交
249 250 251 252 253
func (c *Controller) UrlFor(endpoint string, values ...string) string {
	if len(endpoint) <= 0 {
		return ""
	}
	if endpoint[0] == '.' {
傅小黑 已提交
254
		return UrlFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
A
astaxie 已提交
255 256 257 258 259
	} else {
		return UrlFor(endpoint, values...)
	}
}

260
// ServeJson sends a json response with encoding charset.
A
astaxie 已提交
261
func (c *Controller) ServeJson(encoding ...bool) {
A
astaxie 已提交
262 263
	var hasIndent bool
	var hasencoding bool
264
	if RunMode == "prod" {
A
astaxie 已提交
265
		hasIndent = false
266
	} else {
A
astaxie 已提交
267
		hasIndent = true
268
	}
A
astaxie 已提交
269
	if len(encoding) > 0 && encoding[0] == true {
A
astaxie 已提交
270
		hasencoding = true
A
astaxie 已提交
271
	}
A
astaxie 已提交
272
	c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
A
#2  
astaxie 已提交
273 274
}

傅小黑 已提交
275
// ServeJsonp sends a jsonp response.
L
lw 已提交
276
func (c *Controller) ServeJsonp() {
A
astaxie 已提交
277
	var hasIndent bool
278
	if RunMode == "prod" {
A
astaxie 已提交
279
		hasIndent = false
280
	} else {
A
astaxie 已提交
281
		hasIndent = true
L
lw 已提交
282
	}
A
astaxie 已提交
283
	c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
L
lw 已提交
284 285
}

傅小黑 已提交
286
// ServeXml sends xml response.
A
#2  
astaxie 已提交
287
func (c *Controller) ServeXml() {
A
astaxie 已提交
288
	var hasIndent bool
289
	if RunMode == "prod" {
A
astaxie 已提交
290
		hasIndent = false
291
	} else {
A
astaxie 已提交
292
		hasIndent = true
293
	}
A
astaxie 已提交
294
	c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
A
#2  
astaxie 已提交
295 296
}

A
astaxie 已提交
297 298 299 300 301 302 303 304 305 306 307 308 309 310
// 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()
	}
}

311
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
312
func (c *Controller) Input() url.Values {
A
astaxie 已提交
313
	if c.Ctx.Request.Form == nil {
314 315
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
316 317
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
318

319
// ParseForm maps input data map to obj struct.
320 321 322 323
func (c *Controller) ParseForm(obj interface{}) error {
	return ParseForm(c.Input(), obj)
}

324
// GetString returns the input value by key string.
325
func (c *Controller) GetString(key string) string {
A
astaxie 已提交
326
	return c.Ctx.Input.Query(key)
327 328
}

329 330
// 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 已提交
331
func (c *Controller) GetStrings(key string) []string {
A
asta.xie 已提交
332 333
	f := c.Input()
	if f == nil {
Y
yecrane 已提交
334 335
		return []string{}
	}
A
asta.xie 已提交
336
	vs := f[key]
A
fix #87  
astaxie 已提交
337 338 339 340
	if len(vs) > 0 {
		return vs
	}
	return []string{}
Y
yecrane 已提交
341 342
}

343
// GetInt returns input value as int64.
344
func (c *Controller) GetInt(key string) (int64, error) {
A
astaxie 已提交
345
	return strconv.ParseInt(c.Ctx.Input.Query(key), 10, 64)
346 347
}

348
// GetBool returns input value as bool.
349
func (c *Controller) GetBool(key string) (bool, error) {
A
astaxie 已提交
350
	return strconv.ParseBool(c.Ctx.Input.Query(key))
351 352
}

353
// GetFloat returns input value as float64.
A
astaxie 已提交
354
func (c *Controller) GetFloat(key string) (float64, error) {
A
astaxie 已提交
355
	return strconv.ParseFloat(c.Ctx.Input.Query(key), 64)
A
astaxie 已提交
356 357
}

358 359
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
A
astaxie 已提交
360 361 362 363
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

364 365
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
A
astaxie 已提交
366 367 368 369 370 371
func (c *Controller) SaveToFile(fromfile, tofile string) error {
	file, _, err := c.Ctx.Request.FormFile(fromfile)
	if err != nil {
		return err
	}
	defer file.Close()
傅小黑 已提交
372
	f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
A
astaxie 已提交
373 374 375 376 377 378 379 380
	if err != nil {
		return err
	}
	defer f.Close()
	io.Copy(f, file)
	return nil
}

381
// StartSession starts session and load old session data info this controller.
A
astaxie 已提交
382 383
func (c *Controller) StartSession() session.SessionStore {
	if c.CruSession == nil {
384
		c.CruSession = c.Ctx.Input.CruSession
A
astaxie 已提交
385 386
	}
	return c.CruSession
X
xiemengjun 已提交
387
}
A
session  
astaxie 已提交
388

389
// SetSession puts value into session.
390
func (c *Controller) SetSession(name interface{}, value interface{}) {
A
astaxie 已提交
391 392 393 394
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Set(name, value)
A
session  
astaxie 已提交
395 396
}

397
// GetSession gets value from session.
398
func (c *Controller) GetSession(name interface{}) interface{} {
A
astaxie 已提交
399 400 401 402
	if c.CruSession == nil {
		c.StartSession()
	}
	return c.CruSession.Get(name)
A
session  
astaxie 已提交
403 404
}

405
// SetSession removes value from session.
406
func (c *Controller) DelSession(name interface{}) {
A
astaxie 已提交
407 408 409 410
	if c.CruSession == nil {
		c.StartSession()
	}
	c.CruSession.Delete(name)
A
session  
astaxie 已提交
411
}
A
fix #87  
astaxie 已提交
412

413 414
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
415
func (c *Controller) SessionRegenerateID() {
416 417 418
	if c.CruSession != nil {
		c.CruSession.SessionRelease(c.Ctx.ResponseWriter)
	}
419 420 421 422
	c.CruSession = GlobalSessions.SessionRegenerateId(c.Ctx.ResponseWriter, c.Ctx.Request)
	c.Ctx.Input.CruSession = c.CruSession
}

423
// DestroySession cleans session data and session cookie.
A
astaxie 已提交
424
func (c *Controller) DestroySession() {
425
	c.Ctx.Input.CruSession.Flush()
A
astaxie 已提交
426 427 428
	GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}

429
// IsAjax returns this request is ajax or not.
A
fix #87  
astaxie 已提交
430
func (c *Controller) IsAjax() bool {
A
astaxie 已提交
431
	return c.Ctx.Input.IsAjax()
A
fix #87  
astaxie 已提交
432
}
A
astaxie 已提交
433

434
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
435
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
436
	return c.Ctx.GetSecureCookie(Secret, key)
437 438
}

439
// SetSecureCookie puts value into cookie after encoded the value.
440 441
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
	c.Ctx.SetSecureCookie(Secret, name, value, others...)
442 443
}

444
// XsrfToken creates a xsrf token string and returns.
A
astaxie 已提交
445 446
func (c *Controller) XsrfToken() string {
	if c._xsrf_token == "" {
447 448
		token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
		if !ok {
A
astaxie 已提交
449
			var expire int64
A
astaxie 已提交
450
			if c.XSRFExpire > 0 {
A
astaxie 已提交
451
				expire = int64(c.XSRFExpire)
A
astaxie 已提交
452
			} else {
A
astaxie 已提交
453
				expire = int64(XSRFExpire)
A
astaxie 已提交
454
			}
S
slene 已提交
455
			token = string(utils.RandomCreateBytes(15))
456
			c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
A
astaxie 已提交
457 458 459 460 461 462
		}
		c._xsrf_token = token
	}
	return c._xsrf_token
}

463 464 465
// 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 已提交
466
func (c *Controller) CheckXsrfCookie() bool {
467 468 469
	if !c.EnableXSRF {
		return true
	}
A
astaxie 已提交
470 471 472 473 474 475 476 477 478
	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 已提交
479
	} else if c._xsrf_token != token {
A
astaxie 已提交
480 481 482 483 484
		c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
	}
	return true
}

485
// XsrfFormHtml writes an input field contains xsrf token value.
A
astaxie 已提交
486 487
func (c *Controller) XsrfFormHtml() string {
	return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
傅小黑 已提交
488
		c._xsrf_token + "\"/>"
A
astaxie 已提交
489
}
A
fix #18  
astaxie 已提交
490

491
// GetControllerAndAction gets the executing controller name and action name.
492 493
func (c *Controller) GetControllerAndAction() (controllerName, actionName string) {
	return c.controllerName, c.actionName
A
fix #18  
astaxie 已提交
494
}