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 67
	c.Data = make(map[interface{}]interface{})
	c.Layout = ""
	c.TplNames = ""
68 69
	c.controllerName = controllerName
	c.actionName = actionName
A
#2  
astaxie 已提交
70 71
	c.Ctx = ctx
	c.TplExt = "tpl"
A
astaxie 已提交
72
	c.AppController = app
73
	c.EnableReander = true
74
	c.Data = ctx.Input.Data
A
#2  
astaxie 已提交
75 76
}

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

}

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

}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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