controller.go 12.8 KB
Newer Older
A
#2  
astaxie 已提交
1 2 3 4
package beego

import (
	"bytes"
A
astaxie 已提交
5
	"errors"
A
#2  
astaxie 已提交
6
	"html/template"
A
astaxie 已提交
7
	"io"
A
#2  
astaxie 已提交
8
	"io/ioutil"
A
astaxie 已提交
9
	"mime/multipart"
A
#2  
astaxie 已提交
10 11
	"net/http"
	"net/url"
A
astaxie 已提交
12
	"os"
A
astaxie 已提交
13
	"reflect"
A
#2  
astaxie 已提交
14
	"strconv"
A
astaxie 已提交
15
	"strings"
A
astaxie 已提交
16 17 18

	"github.com/astaxie/beego/context"
	"github.com/astaxie/beego/session"
S
slene 已提交
19
	"github.com/astaxie/beego/utils"
A
#2  
astaxie 已提交
20 21
)

A
astaxie 已提交
22
var (
23
	// custom error when user stop request handler manually.
A
astaxie 已提交
24 25 26
	USERSTOPRUN = errors.New("User stop run")
)

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

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

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

76
// Prepare runs after Init before request function execution.
A
#2  
astaxie 已提交
77 78 79 80
func (c *Controller) Prepare() {

}

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

}

86
// Get adds a request function to handle GET request.
A
#2  
astaxie 已提交
87 88 89 90
func (c *Controller) Get() {
	http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}

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

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

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

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

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

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

121
// Render sends the response with rendered template bytes as text/html type.
A
#2  
astaxie 已提交
122
func (c *Controller) Render() error {
123 124 125
	if !c.EnableReander {
		return nil
	}
A
astaxie 已提交
126 127 128 129 130
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
131 132
		c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
		c.Ctx.Output.Body(rb)
A
astaxie 已提交
133 134 135 136
	}
	return nil
}

137
// RenderString returns the rendered template string. Do not send out response.
A
astaxie 已提交
138 139 140 141 142
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

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

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

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

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

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

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

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

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

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

286
// Input returns the input data map from POST or PUT request body and query string.
A
#2  
astaxie 已提交
287
func (c *Controller) Input() url.Values {
288
	ct := c.Ctx.Request.Header.Get("Content-Type")
A
astaxie 已提交
289
	if strings.Contains(ct, "multipart/form-data") {
290 291 292 293
		c.Ctx.Request.ParseMultipartForm(MaxMemory) //64MB
	} else {
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
294 295
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
296

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

302
// GetString returns the input value by key string.
303 304 305 306
func (c *Controller) GetString(key string) string {
	return c.Input().Get(key)
}

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

321
// GetInt returns input value as int64.
322 323 324 325
func (c *Controller) GetInt(key string) (int64, error) {
	return strconv.ParseInt(c.Input().Get(key), 10, 64)
}

326
// GetBool returns input value as bool.
327 328 329 330
func (c *Controller) GetBool(key string) (bool, error) {
	return strconv.ParseBool(c.Input().Get(key))
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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