1
0
mirror of https://github.com/astaxie/beego.git synced 2024-11-24 19:20:55 +00:00
Beego/controller.go

707 lines
21 KiB
Go
Raw Normal View History

2014-08-18 08:41:43 +00:00
// Copyright 2014 beego Author. All Rights Reserved.
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// http://www.apache.org/licenses/LICENSE-2.0
2014-07-03 15:40:21 +00:00
//
2014-08-18 08:41:43 +00:00
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
2012-12-19 08:20:55 +00:00
package beego
import (
"bytes"
2013-04-21 03:28:20 +00:00
"errors"
2019-04-03 02:19:09 +00:00
"fmt"
2012-12-19 08:20:55 +00:00
"html/template"
2013-04-16 10:20:55 +00:00
"io"
2013-04-09 15:33:48 +00:00
"mime/multipart"
2012-12-19 08:20:55 +00:00
"net/http"
"net/url"
2013-04-16 10:20:55 +00:00
"os"
"reflect"
2012-12-19 08:20:55 +00:00
"strconv"
2013-04-09 16:24:28 +00:00
"strings"
2013-12-03 13:37:39 +00:00
"github.com/astaxie/beego/context"
2017-04-25 15:39:42 +00:00
"github.com/astaxie/beego/context/param"
"github.com/astaxie/beego/session"
2012-12-19 08:20:55 +00:00
)
2013-12-17 00:53:15 +00:00
var (
2015-09-08 02:43:42 +00:00
// ErrAbort custom error when user stop request handler manually.
2019-01-22 11:09:57 +00:00
ErrAbort = errors.New("user stop run")
2015-09-08 02:43:42 +00:00
// GlobalControllerRouter store comments with controller. pkgpath+controller:comments
GlobalControllerRouter = make(map[string][]ControllerComments)
2013-12-17 00:53:15 +00:00
)
// ControllerFilter store the filter for controller
type ControllerFilter struct {
Pattern string
Pos int
Filter FilterFunc
ReturnOnOutput bool
ResetParams bool
}
// ControllerFilterComments store the comment for controller level filter
type ControllerFilterComments struct {
Pattern string
Pos int
Filter string // NOQA
ReturnOnOutput bool
ResetParams bool
}
// ControllerImportComments store the import comment for controller needed
type ControllerImportComments struct {
ImportPath string
ImportAlias string
}
2015-09-08 02:43:42 +00:00
// ControllerComments store the comment for the controller method
2014-06-09 02:11:37 +00:00
type ControllerComments struct {
Method string
Router string
Filters []*ControllerFilter
ImportComments []*ControllerImportComments
FilterComments []*ControllerFilterComments
AllowHTTPMethods []string
Params []map[string]string
2017-04-21 12:26:41 +00:00
MethodParams []*param.MethodParam
2014-06-09 02:11:37 +00:00
}
2017-07-18 16:52:27 +00:00
// ControllerCommentsSlice implements the sort interface
2017-07-15 09:26:20 +00:00
type ControllerCommentsSlice []ControllerComments
2019-04-03 02:19:09 +00:00
func (p ControllerCommentsSlice) Len() int { return len(p) }
func (p ControllerCommentsSlice) Less(i, j int) bool { return p[i].Router < p[j].Router }
func (p ControllerCommentsSlice) Swap(i, j int) { p[i], p[j] = p[j], p[i] }
2017-07-15 09:26:20 +00:00
// Controller defines some basic http request handler operations, such as
// http context, template and view, session and xsrf.
2012-12-19 08:20:55 +00:00
type Controller struct {
// context data
Ctx *context.Context
Data map[interface{}]interface{}
2015-12-21 08:23:31 +00:00
// route controller info
controllerName string
actionName string
2015-12-21 08:23:31 +00:00
methodMapping map[string]func() //method:routertree
AppController interface{}
// template data
TplName string
2017-02-07 16:28:03 +00:00
ViewPath string
Layout string
LayoutSections map[string]string // the key is the section name and the value is the template name
TplPrefix string
TplExt string
2014-05-08 02:51:29 +00:00
EnableRender bool
2015-12-21 08:23:31 +00:00
// xsrf data
_xsrfToken string
XSRFExpire int
EnableXSRF bool
2015-12-21 08:23:31 +00:00
// session
CruSession session.Store
2012-12-19 08:20:55 +00:00
}
// ControllerInterface is an interface to uniform all controller handler.
2012-12-19 08:20:55 +00:00
type ControllerInterface interface {
Init(ct *context.Context, controllerName, actionName string, app interface{})
2012-12-19 08:20:55 +00:00
Prepare()
Get()
Post()
Delete()
Put()
Head()
Patch()
Options()
2019-03-27 05:34:46 +00:00
Trace()
2012-12-19 08:20:55 +00:00
Finish()
Render() error
2015-09-08 13:41:38 +00:00
XSRFToken() string
CheckXSRFCookie() bool
2014-06-10 03:02:41 +00:00
HandlerFunc(fn string) bool
2014-06-08 12:24:01 +00:00
URLMapping()
2012-12-19 08:20:55 +00:00
}
// Init generates default values of controller operations.
func (c *Controller) Init(ctx *context.Context, controllerName, actionName string, app interface{}) {
2012-12-19 08:20:55 +00:00
c.Layout = ""
c.TplName = ""
c.controllerName = controllerName
c.actionName = actionName
2012-12-19 08:20:55 +00:00
c.Ctx = ctx
c.TplExt = "tpl"
c.AppController = app
2014-05-08 02:51:29 +00:00
c.EnableRender = true
c.EnableXSRF = true
2015-12-16 15:11:03 +00:00
c.Data = ctx.Input.Data()
2014-06-09 02:11:37 +00:00
c.methodMapping = make(map[string]func())
2012-12-19 08:20:55 +00:00
}
// Prepare runs after Init before request function execution.
2015-12-21 08:23:31 +00:00
func (c *Controller) Prepare() {}
2012-12-19 08:20:55 +00:00
// Finish runs after request function execution.
2015-12-21 08:23:31 +00:00
func (c *Controller) Finish() {}
2013-05-08 05:56:48 +00:00
// Get adds a request function to handle GET request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Get() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
// Post adds a request function to handle POST request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Post() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
// Delete adds a request function to handle DELETE request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Delete() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
// Put adds a request function to handle PUT request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Put() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
// Head adds a request function to handle HEAD request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Head() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
// Patch adds a request function to handle PATCH request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Patch() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
// Options adds a request function to handle OPTIONS request.
2012-12-19 08:20:55 +00:00
func (c *Controller) Options() {
2019-01-22 11:09:57 +00:00
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", http.StatusMethodNotAllowed)
2012-12-19 08:20:55 +00:00
}
2019-03-27 05:34:46 +00:00
// Trace adds a request function to handle Trace request.
2019-03-27 05:43:27 +00:00
// this method SHOULD NOT be overridden.
2019-03-27 05:34:46 +00:00
// https://tools.ietf.org/html/rfc7231#section-4.3.8
// The TRACE method requests a remote, application-level loop-back of
// the request message. The final recipient of the request SHOULD
// reflect the message received, excluding some fields described below,
// back to the client as the message body of a 200 (OK) response with a
// Content-Type of "message/http" (Section 8.3.1 of [RFC7230]).
func (c *Controller) Trace() {
ts := func(h http.Header) (hs string) {
for k, v := range h {
hs += fmt.Sprintf("\r\n%s: %s", k, v)
}
return
}
hs := fmt.Sprintf("\r\nTRACE %s %s%s\r\n", c.Ctx.Request.RequestURI, c.Ctx.Request.Proto, ts(c.Ctx.Request.Header))
c.Ctx.Output.Header("Content-Type", "message/http")
c.Ctx.Output.Header("Content-Length", fmt.Sprint(len(hs)))
c.Ctx.Output.Header("Cache-Control", "no-cache, no-store, must-revalidate")
2019-03-27 05:34:46 +00:00
c.Ctx.WriteString(hs)
}
2015-09-08 02:43:42 +00:00
// HandlerFunc call function with the name
2014-06-10 03:02:41 +00:00
func (c *Controller) HandlerFunc(fnname string) bool {
2014-06-09 02:11:37 +00:00
if v, ok := c.methodMapping[fnname]; ok {
2014-06-08 12:24:01 +00:00
v()
2014-06-10 03:02:41 +00:00
return true
2014-06-08 12:24:01 +00:00
}
2015-09-08 02:43:42 +00:00
return false
2014-06-08 12:24:01 +00:00
}
// URLMapping register the internal Controller router.
2015-12-21 08:23:31 +00:00
func (c *Controller) URLMapping() {}
2014-06-08 12:24:01 +00:00
2015-09-08 02:43:42 +00:00
// Mapping the method to function
2014-06-09 02:11:37 +00:00
func (c *Controller) Mapping(method string, fn func()) {
c.methodMapping[method] = fn
2014-06-08 12:24:01 +00:00
}
// Render sends the response with rendered template bytes as text/html type.
2012-12-19 08:20:55 +00:00
func (c *Controller) Render() error {
2014-05-08 02:51:29 +00:00
if !c.EnableRender {
return nil
}
2013-03-14 13:17:37 +00:00
rb, err := c.RenderBytes()
if err != nil {
return err
}
2016-12-14 17:19:31 +00:00
if c.Ctx.ResponseWriter.Header().Get("Content-Type") == "" {
c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
}
2016-02-12 03:36:25 +00:00
return c.Ctx.Output.Body(rb)
2013-03-14 13:17:37 +00:00
}
// RenderString returns the rendered template string. Do not send out response.
func (c *Controller) RenderString() (string, error) {
b, e := c.RenderBytes()
return string(b), e
}
2013-12-28 12:14:36 +00:00
// RenderBytes returns the bytes of rendered template string. Do not send out response.
2013-03-14 13:17:37 +00:00
func (c *Controller) RenderBytes() ([]byte, error) {
2016-03-04 06:49:16 +00:00
buf, err := c.renderTemplate()
//if the controller has set layout, then first get the tplName's content set the content to the layout
if err == nil && c.Layout != "" {
2015-12-21 08:23:31 +00:00
c.Data["LayoutContent"] = template.HTML(buf.String())
if c.LayoutSections != nil {
for sectionName, sectionTpl := range c.LayoutSections {
if sectionTpl == "" {
c.Data[sectionName] = ""
continue
}
2015-12-21 08:23:31 +00:00
buf.Reset()
2017-02-07 16:28:03 +00:00
err = ExecuteViewPathTemplate(&buf, sectionTpl, c.viewPath(), c.Data)
if err != nil {
return nil, err
}
2015-12-21 08:23:31 +00:00
c.Data[sectionName] = template.HTML(buf.String())
}
}
2015-12-21 08:23:31 +00:00
buf.Reset()
2017-03-17 17:24:45 +00:00
ExecuteViewPathTemplate(&buf, c.Layout, c.viewPath(), c.Data)
2012-12-19 08:20:55 +00:00
}
2016-03-04 06:49:16 +00:00
return buf.Bytes(), err
}
2015-09-08 02:43:42 +00:00
2016-03-04 06:49:16 +00:00
func (c *Controller) renderTemplate() (bytes.Buffer, error) {
var buf bytes.Buffer
if c.TplName == "" {
c.TplName = strings.ToLower(c.controllerName) + "/" + strings.ToLower(c.actionName) + "." + c.TplExt
2015-09-08 02:43:42 +00:00
}
2016-07-14 08:48:49 +00:00
if c.TplPrefix != "" {
c.TplName = c.TplPrefix + c.TplName
2015-09-08 02:43:42 +00:00
}
if BConfig.RunMode == DEV {
2016-03-04 06:49:16 +00:00
buildFiles := []string{c.TplName}
if c.Layout != "" {
buildFiles = append(buildFiles, c.Layout)
if c.LayoutSections != nil {
for _, sectionTpl := range c.LayoutSections {
if sectionTpl == "" {
continue
}
buildFiles = append(buildFiles, sectionTpl)
2016-03-04 06:49:16 +00:00
}
}
2016-03-04 04:00:43 +00:00
}
2017-03-17 17:24:45 +00:00
BuildTemplate(c.viewPath(), buildFiles...)
2015-09-08 02:43:42 +00:00
}
2017-02-07 16:28:03 +00:00
return buf, ExecuteViewPathTemplate(&buf, c.TplName, c.viewPath(), c.Data)
}
func (c *Controller) viewPath() string {
if c.ViewPath == "" {
return BConfig.WebConfig.ViewsPath
}
return c.ViewPath
2012-12-19 08:20:55 +00:00
}
// Redirect sends the redirection response to url with status code.
2012-12-19 08:20:55 +00:00
func (c *Controller) Redirect(url string, code int) {
2019-02-14 15:29:26 +00:00
LogAccess(c.Ctx, nil, code)
2012-12-19 08:20:55 +00:00
c.Ctx.Redirect(code, url)
}
2018-11-09 09:54:20 +00:00
// SetData set the data depending on the accepted
func (c *Controller) SetData(data interface{}) {
accept := c.Ctx.Input.Header("Accept")
switch accept {
case context.ApplicationYAML:
c.Data["yaml"] = data
case context.ApplicationXML, context.TextXML:
c.Data["xml"] = data
default:
c.Data["json"] = data
}
2012-12-19 08:20:55 +00:00
}
2015-09-08 02:43:42 +00:00
// Abort stops controller handler and show the error data if code is defined in ErrorMap or code string.
2013-05-06 16:17:25 +00:00
func (c *Controller) Abort(code string) {
status, err := strconv.Atoi(code)
2015-02-26 16:12:10 +00:00
if err != nil {
status = 200
}
2015-02-26 16:12:10 +00:00
c.CustomAbort(status, code)
}
// CustomAbort stops controller handler and show the error data, it's similar Aborts, but support status code and body.
func (c *Controller) CustomAbort(status int, body string) {
2016-04-18 11:37:38 +00:00
// first panic from ErrorMaps, it is user defined error functions.
2015-02-26 16:12:10 +00:00
if _, ok := ErrorMaps[body]; ok {
c.Ctx.Output.Status = status
2015-02-26 16:12:10 +00:00
panic(body)
}
// last panic user string
c.Ctx.ResponseWriter.WriteHeader(status)
2015-02-26 16:12:10 +00:00
c.Ctx.ResponseWriter.Write([]byte(body))
2015-09-08 02:43:42 +00:00
panic(ErrAbort)
}
// StopRun makes panic of USERSTOPRUN error and go to recover function if defined.
func (c *Controller) StopRun() {
2015-09-08 02:43:42 +00:00
panic(ErrAbort)
2013-05-06 16:17:25 +00:00
}
2015-09-08 02:43:42 +00:00
// URLFor does another controller handler in this request function.
// it goes to this controller method if endpoint is not clear.
2015-09-08 02:43:42 +00:00
func (c *Controller) URLFor(endpoint string, values ...interface{}) string {
2015-12-21 08:23:31 +00:00
if len(endpoint) == 0 {
return ""
}
if endpoint[0] == '.' {
return URLFor(reflect.Indirect(reflect.ValueOf(c.AppController)).Type().Name()+endpoint, values...)
}
2015-09-08 02:43:42 +00:00
return URLFor(endpoint, values...)
}
2015-09-08 02:43:42 +00:00
// ServeJSON sends a json response with encoding charset.
func (c *Controller) ServeJSON(encoding ...bool) {
2015-12-21 08:23:31 +00:00
var (
hasIndent = BConfig.RunMode != PROD
hasEncoding = len(encoding) > 0 && encoding[0]
2015-12-21 08:23:31 +00:00
)
2015-12-21 08:23:31 +00:00
c.Ctx.Output.JSON(c.Data["json"], hasIndent, hasEncoding)
2012-12-19 08:20:55 +00:00
}
2015-09-08 02:43:42 +00:00
// ServeJSONP sends a jsonp response.
func (c *Controller) ServeJSONP() {
hasIndent := BConfig.RunMode != PROD
2015-09-10 07:31:09 +00:00
c.Ctx.Output.JSONP(c.Data["jsonp"], hasIndent)
2013-06-13 09:10:35 +00:00
}
2015-09-08 02:43:42 +00:00
// ServeXML sends xml response.
func (c *Controller) ServeXML() {
hasIndent := BConfig.RunMode != PROD
2015-09-10 07:31:09 +00:00
c.Ctx.Output.XML(c.Data["xml"], hasIndent)
2012-12-19 08:20:55 +00:00
}
2018-11-09 09:54:20 +00:00
// ServeYAML sends yaml response.
2018-05-30 14:06:40 +00:00
func (c *Controller) ServeYAML() {
c.Ctx.Output.YAML(c.Data["yaml"])
}
// ServeFormatted serve YAML, XML OR JSON, depending on the value of the Accept header
func (c *Controller) ServeFormatted(encoding ...bool) {
hasIndent := BConfig.RunMode != PROD
hasEncoding := len(encoding) > 0 && encoding[0]
c.Ctx.Output.ServeFormatted(c.Data, hasIndent, hasEncoding)
}
// Input returns the input data map from POST or PUT request body and query string.
2012-12-19 08:20:55 +00:00
func (c *Controller) Input() url.Values {
2014-04-10 14:20:46 +00:00
if c.Ctx.Request.Form == nil {
c.Ctx.Request.ParseForm()
}
2012-12-19 08:20:55 +00:00
return c.Ctx.Request.Form
}
2013-01-01 15:11:15 +00:00
// ParseForm maps input data map to obj struct.
2013-07-25 14:26:31 +00:00
func (c *Controller) ParseForm(obj interface{}) error {
return ParseForm(c.Input(), obj)
}
// GetString returns the input value by key string or the default value while it's present and input is blank
func (c *Controller) GetString(key string, def ...string) string {
if v := c.Ctx.Input.Query(key); v != "" {
return v
}
2015-12-21 08:23:31 +00:00
if len(def) > 0 {
return def[0]
}
return ""
}
// GetStrings returns the input string slice by key string or the default value while it's present and input is blank
// it's designed for multi-value input field such as checkbox(input[type=checkbox]), multi-selection.
func (c *Controller) GetStrings(key string, def ...[]string) []string {
var defv []string
if len(def) > 0 {
defv = def[0]
}
2015-12-21 08:23:31 +00:00
if f := c.Input(); f == nil {
return defv
2016-01-17 16:18:21 +00:00
} else if vs := f[key]; len(vs) > 0 {
return vs
}
2015-09-08 02:43:42 +00:00
return defv
}
// GetInt returns input as an int or the default value while it's present and input is blank
func (c *Controller) GetInt(key string, def ...int) (int, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
return strconv.Atoi(strv)
}
// GetInt8 return input as an int8 or the default value while it's present and input is blank
func (c *Controller) GetInt8(key string, def ...int8) (int8, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
i64, err := strconv.ParseInt(strv, 10, 8)
return int8(i64), err
}
2016-10-02 07:41:26 +00:00
// GetUint8 return input as an uint8 or the default value while it's present and input is blank
func (c *Controller) GetUint8(key string, def ...uint8) (uint8, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0], nil
}
u64, err := strconv.ParseUint(strv, 10, 8)
return uint8(u64), err
}
// GetInt16 returns input as an int16 or the default value while it's present and input is blank
func (c *Controller) GetInt16(key string, def ...int16) (int16, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
i64, err := strconv.ParseInt(strv, 10, 16)
return int16(i64), err
}
2016-10-02 07:41:26 +00:00
// GetUint16 returns input as an uint16 or the default value while it's present and input is blank
func (c *Controller) GetUint16(key string, def ...uint16) (uint16, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0], nil
}
u64, err := strconv.ParseUint(strv, 10, 16)
return uint16(u64), err
}
// GetInt32 returns input as an int32 or the default value while it's present and input is blank
func (c *Controller) GetInt32(key string, def ...int32) (int32, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
i64, err := strconv.ParseInt(strv, 10, 32)
return int32(i64), err
}
2016-10-02 07:41:26 +00:00
// GetUint32 returns input as an uint32 or the default value while it's present and input is blank
func (c *Controller) GetUint32(key string, def ...uint32) (uint32, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0], nil
}
u64, err := strconv.ParseUint(strv, 10, 32)
return uint32(u64), err
}
// GetInt64 returns input value as int64 or the default value while it's present and input is blank.
func (c *Controller) GetInt64(key string, def ...int64) (int64, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
return strconv.ParseInt(strv, 10, 64)
}
2016-10-02 07:41:26 +00:00
// GetUint64 returns input value as uint64 or the default value while it's present and input is blank.
func (c *Controller) GetUint64(key string, def ...uint64) (uint64, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
return def[0], nil
}
return strconv.ParseUint(strv, 10, 64)
}
// GetBool returns input value as bool or the default value while it's present and input is blank.
func (c *Controller) GetBool(key string, def ...bool) (bool, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
return strconv.ParseBool(strv)
}
// GetFloat returns input value as float64 or the default value while it's present and input is blank.
func (c *Controller) GetFloat(key string, def ...float64) (float64, error) {
strv := c.Ctx.Input.Query(key)
if len(strv) == 0 && len(def) > 0 {
2015-04-01 15:31:40 +00:00
return def[0], nil
}
return strconv.ParseFloat(strv, 64)
2013-09-09 16:00:11 +00:00
}
// GetFile returns the file data in file upload field named as key.
// it returns the first one of multi-uploaded files.
2013-04-09 15:33:48 +00:00
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
return c.Ctx.Request.FormFile(key)
}
// GetFiles return multi-upload files
// files, err:=c.GetFiles("myfiles")
// if err != nil {
// http.Error(w, err.Error(), http.StatusNoContent)
// return
// }
// for i, _ := range files {
// //for each fileheader, get a handle to the actual file
// file, err := files[i].Open()
// defer file.Close()
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// //create destination file making sure the path is writeable.
// dst, err := os.Create("upload/" + files[i].Filename)
// defer dst.Close()
// if err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// //copy the uploaded file to the destination file
// if _, err := io.Copy(dst, file); err != nil {
// http.Error(w, err.Error(), http.StatusInternalServerError)
// return
// }
// }
func (c *Controller) GetFiles(key string) ([]*multipart.FileHeader, error) {
2015-12-21 08:23:31 +00:00
if files, ok := c.Ctx.Request.MultipartForm.File[key]; ok {
return files, nil
}
return nil, http.ErrMissingFile
}
// SaveToFile saves uploaded file to new path.
// it only operates the first one of mutil-upload form file field.
2013-04-16 10:20:55 +00:00
func (c *Controller) SaveToFile(fromfile, tofile string) error {
file, _, err := c.Ctx.Request.FormFile(fromfile)
if err != nil {
return err
}
defer file.Close()
f, err := os.OpenFile(tofile, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0666)
2013-04-16 10:20:55 +00:00
if err != nil {
return err
}
defer f.Close()
io.Copy(f, file)
return nil
}
// StartSession starts session and load old session data info this controller.
2015-09-12 14:53:55 +00:00
func (c *Controller) StartSession() session.Store {
2013-05-07 07:36:43 +00:00
if c.CruSession == nil {
c.CruSession = c.Ctx.Input.CruSession
2013-05-07 07:36:43 +00:00
}
return c.CruSession
2013-01-01 15:11:15 +00:00
}
// SetSession puts value into session.
func (c *Controller) SetSession(name interface{}, value interface{}) {
2013-05-07 07:36:43 +00:00
if c.CruSession == nil {
c.StartSession()
}
c.CruSession.Set(name, value)
}
// GetSession gets value from session.
func (c *Controller) GetSession(name interface{}) interface{} {
2013-05-07 07:36:43 +00:00
if c.CruSession == nil {
c.StartSession()
}
return c.CruSession.Get(name)
}
2015-09-08 02:43:42 +00:00
// DelSession removes value from session.
func (c *Controller) DelSession(name interface{}) {
2013-05-07 07:36:43 +00:00
if c.CruSession == nil {
c.StartSession()
}
c.CruSession.Delete(name)
}
2013-07-02 01:45:12 +00:00
// SessionRegenerateID regenerates session id for this session.
// the session data have no changes.
func (c *Controller) SessionRegenerateID() {
if c.CruSession != nil {
c.CruSession.SessionRelease(c.Ctx.ResponseWriter)
}
2015-09-12 14:53:55 +00:00
c.CruSession = GlobalSessions.SessionRegenerateID(c.Ctx.ResponseWriter, c.Ctx.Request)
c.Ctx.Input.CruSession = c.CruSession
}
// DestroySession cleans session data and session cookie.
2013-08-10 15:58:25 +00:00
func (c *Controller) DestroySession() {
c.Ctx.Input.CruSession.Flush()
2016-01-18 08:11:27 +00:00
c.Ctx.Input.CruSession = nil
2013-08-10 15:58:25 +00:00
GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}
// IsAjax returns this request is ajax or not.
2013-07-02 01:45:12 +00:00
func (c *Controller) IsAjax() bool {
2013-09-09 16:00:11 +00:00
return c.Ctx.Input.IsAjax()
2013-07-02 01:45:12 +00:00
}
2013-07-08 08:17:08 +00:00
// GetSecureCookie returns decoded cookie value from encoded browser cookie values.
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
return c.Ctx.GetSecureCookie(Secret, key)
}
// SetSecureCookie puts value into cookie after encoded the value.
func (c *Controller) SetSecureCookie(Secret, name, value string, others ...interface{}) {
c.Ctx.SetSecureCookie(Secret, name, value, others...)
}
2015-09-08 02:43:42 +00:00
// XSRFToken creates a CSRF token string and returns.
func (c *Controller) XSRFToken() string {
if c._xsrfToken == "" {
2015-12-21 08:23:31 +00:00
expire := int64(BConfig.WebConfig.XSRFExpire)
if c.XSRFExpire > 0 {
expire = int64(c.XSRFExpire)
2013-07-08 08:17:08 +00:00
}
2016-01-15 06:07:37 +00:00
c._xsrfToken = c.Ctx.XSRFToken(BConfig.WebConfig.XSRFKey, expire)
2013-07-08 08:17:08 +00:00
}
2015-09-08 02:43:42 +00:00
return c._xsrfToken
2013-07-08 08:17:08 +00:00
}
2015-09-08 02:43:42 +00:00
// 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".
2015-09-08 02:43:42 +00:00
func (c *Controller) CheckXSRFCookie() bool {
if !c.EnableXSRF {
return true
}
2015-09-10 07:31:09 +00:00
return c.Ctx.CheckXSRFCookie()
2013-07-08 08:17:08 +00:00
}
2015-09-08 02:43:42 +00:00
// XSRFFormHTML writes an input field contains xsrf token value.
func (c *Controller) XSRFFormHTML() string {
return `<input type="hidden" name="_xsrf" value="` +
c.XSRFToken() + `" />`
2013-07-08 08:17:08 +00:00
}
// GetControllerAndAction gets the executing controller name and action name.
2015-12-21 08:23:31 +00:00
func (c *Controller) GetControllerAndAction() (string, string) {
return c.controllerName, c.actionName
}