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

390 lines
8.7 KiB
Go
Raw Normal View History

2012-12-19 08:20:55 +00:00
package beego
import (
"bytes"
2013-07-08 08:17:08 +00:00
"crypto/hmac"
"crypto/sha1"
"encoding/base64"
2013-04-21 03:28:20 +00:00
"errors"
2013-07-08 08:17:08 +00:00
"fmt"
2013-09-09 16:00:11 +00:00
"github.com/astaxie/beego/context"
"github.com/astaxie/beego/session"
2012-12-19 08:20:55 +00:00
"html/template"
2013-04-16 10:20:55 +00:00
"io"
2012-12-19 08:20:55 +00:00
"io/ioutil"
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"
2012-12-19 08:20:55 +00:00
"strconv"
2013-04-09 16:24:28 +00:00
"strings"
2013-07-08 08:17:08 +00:00
"time"
2012-12-19 08:20:55 +00:00
)
type Controller struct {
Ctx *context.Context
Data map[interface{}]interface{}
ChildName string
TplNames string
Layout string
TplExt string
_xsrf_token string
gotofunc string
CruSession session.SessionStore
XSRFExpire int
AppController interface{}
2012-12-19 08:20:55 +00:00
}
type ControllerInterface interface {
2013-09-28 15:37:05 +00:00
Init(ct *context.Context, childName string, app interface{})
2012-12-19 08:20:55 +00:00
Prepare()
Get()
Post()
Delete()
Put()
Head()
Patch()
Options()
Finish()
Render() error
}
func (c *Controller) Init(ctx *context.Context, childName string, app interface{}) {
2012-12-19 08:20:55 +00:00
c.Data = make(map[interface{}]interface{})
c.Layout = ""
c.TplNames = ""
2013-09-09 16:00:11 +00:00
c.ChildName = childName
2012-12-19 08:20:55 +00:00
c.Ctx = ctx
c.TplExt = "tpl"
c.AppController = app
2012-12-19 08:20:55 +00:00
}
func (c *Controller) Prepare() {
}
func (c *Controller) Finish() {
2013-05-08 05:56:48 +00:00
}
func (c *Controller) Destructor() {
2013-05-07 07:36:43 +00:00
if c.CruSession != nil {
c.CruSession.SessionRelease()
}
2012-12-19 08:20:55 +00:00
}
func (c *Controller) Get() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Post() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Delete() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Put() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Head() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Patch() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Options() {
http.Error(c.Ctx.ResponseWriter, "Method Not Allowed", 405)
}
func (c *Controller) Render() error {
2013-03-14 13:17:37 +00:00
rb, err := c.RenderBytes()
if err != nil {
return err
} else {
2013-09-09 16:00:11 +00:00
c.Ctx.Output.Header("Content-Type", "text/html; charset=utf-8")
c.Ctx.Output.Body(rb)
2013-03-14 13:17:37 +00:00
}
return nil
}
func (c *Controller) RenderString() (string, error) {
b, e := c.RenderBytes()
return string(b), e
}
2013-03-14 13:17:37 +00:00
func (c *Controller) RenderBytes() ([]byte, error) {
2012-12-19 08:20:55 +00:00
//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 == "" {
2013-07-30 14:17:16 +00:00
c.TplNames = c.ChildName + "/" + strings.ToLower(c.Ctx.Request.Method) + "." + c.TplExt
2012-12-19 08:20:55 +00:00
}
if RunMode == "dev" {
BuildTemplate(ViewsPath)
}
2012-12-19 08:20:55 +00:00
newbytes := bytes.NewBufferString("")
2013-09-12 09:20:32 +00:00
if _, ok := BeeTemplates[c.TplNames]; !ok {
2013-04-21 03:28:20 +00:00
panic("can't find templatefile in the path:" + c.TplNames)
return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
}
2013-09-12 09:20:32 +00:00
err := BeeTemplates[c.TplNames].ExecuteTemplate(newbytes, c.TplNames, c.Data)
2013-09-12 05:44:12 +00:00
if err != nil {
2013-09-12 07:24:08 +00:00
Trace("template Execute err:", err)
2013-09-12 05:44:12 +00:00
}
2012-12-19 08:20:55 +00:00
tplcontent, _ := ioutil.ReadAll(newbytes)
c.Data["LayoutContent"] = template.HTML(string(tplcontent))
2013-03-14 13:17:37 +00:00
ibytes := bytes.NewBufferString("")
2013-09-12 09:20:32 +00:00
err = BeeTemplates[c.Layout].ExecuteTemplate(ibytes, c.Layout, c.Data)
2012-12-19 08:20:55 +00:00
if err != nil {
Trace("template Execute err:", err)
}
2013-03-14 13:17:37 +00:00
icontent, _ := ioutil.ReadAll(ibytes)
return icontent, nil
2012-12-19 08:20:55 +00:00
} else {
if c.TplNames == "" {
2013-07-30 14:45:50 +00:00
c.TplNames = c.ChildName + "/" + strings.ToLower(c.Ctx.Request.Method) + "." + c.TplExt
2012-12-19 08:20:55 +00:00
}
if RunMode == "dev" {
BuildTemplate(ViewsPath)
}
2013-03-14 13:17:37 +00:00
ibytes := bytes.NewBufferString("")
2013-09-12 09:20:32 +00:00
if _, ok := BeeTemplates[c.TplNames]; !ok {
2013-04-21 03:28:20 +00:00
panic("can't find templatefile in the path:" + c.TplNames)
return []byte{}, errors.New("can't find templatefile in the path:" + c.TplNames)
}
2013-09-12 09:20:32 +00:00
err := BeeTemplates[c.TplNames].ExecuteTemplate(ibytes, c.TplNames, c.Data)
2012-12-19 08:20:55 +00:00
if err != nil {
2013-09-12 09:20:32 +00:00
Trace("template Execute err:", err)
2012-12-19 08:20:55 +00:00
}
2013-03-14 13:17:37 +00:00
icontent, _ := ioutil.ReadAll(ibytes)
return icontent, nil
2012-12-19 08:20:55 +00:00
}
2013-03-14 13:17:37 +00:00
return []byte{}, nil
2012-12-19 08:20:55 +00:00
}
func (c *Controller) Redirect(url string, code int) {
c.Ctx.Redirect(code, url)
}
2013-05-06 16:17:25 +00:00
func (c *Controller) Abort(code string) {
panic(code)
}
2013-08-06 08:37:41 +00:00
func (c *Controller) ServeJson(encoding ...bool) {
2013-09-09 16:00:11 +00:00
var hasIndent bool
var hasencoding bool
if RunMode == "prod" {
2013-09-09 16:00:11 +00:00
hasIndent = false
} else {
2013-09-09 16:00:11 +00:00
hasIndent = true
}
2013-08-06 08:37:41 +00:00
if len(encoding) > 0 && encoding[0] == true {
2013-09-09 16:00:11 +00:00
hasencoding = true
2013-08-06 08:37:41 +00:00
}
2013-09-09 16:00:11 +00:00
c.Ctx.Output.Json(c.Data["json"], hasIndent, hasencoding)
2012-12-19 08:20:55 +00:00
}
2013-06-13 09:10:35 +00:00
func (c *Controller) ServeJsonp() {
2013-09-09 16:00:11 +00:00
var hasIndent bool
if RunMode == "prod" {
2013-09-09 16:00:11 +00:00
hasIndent = false
} else {
2013-09-09 16:00:11 +00:00
hasIndent = true
2013-06-13 09:10:35 +00:00
}
2013-09-09 16:00:11 +00:00
c.Ctx.Output.Jsonp(c.Data["jsonp"], hasIndent)
2013-06-13 09:10:35 +00:00
}
2012-12-19 08:20:55 +00:00
func (c *Controller) ServeXml() {
2013-09-09 16:00:11 +00:00
var hasIndent bool
if RunMode == "prod" {
2013-09-09 16:00:11 +00:00
hasIndent = false
} else {
2013-09-09 16:00:11 +00:00
hasIndent = true
}
2013-09-09 16:00:11 +00:00
c.Ctx.Output.Xml(c.Data["xml"], hasIndent)
2012-12-19 08:20:55 +00:00
}
func (c *Controller) Input() url.Values {
ct := c.Ctx.Request.Header.Get("Content-Type")
2013-04-09 16:24:28 +00:00
if strings.Contains(ct, "multipart/form-data") {
c.Ctx.Request.ParseMultipartForm(MaxMemory) //64MB
} else {
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
2013-07-25 14:26:31 +00:00
func (c *Controller) ParseForm(obj interface{}) error {
return ParseForm(c.Input(), obj)
}
func (c *Controller) GetString(key string) string {
return c.Input().Get(key)
}
func (c *Controller) GetStrings(key string) []string {
2013-07-02 01:45:12 +00:00
r := c.Ctx.Request
if r.Form == nil {
return []string{}
}
2013-07-02 01:45:12 +00:00
vs := r.Form[key]
if len(vs) > 0 {
return vs
}
return []string{}
}
func (c *Controller) GetInt(key string) (int64, error) {
return strconv.ParseInt(c.Input().Get(key), 10, 64)
}
func (c *Controller) GetBool(key string) (bool, error) {
return strconv.ParseBool(c.Input().Get(key))
}
2013-09-09 16:00:11 +00:00
func (c *Controller) GetFloat(key string) (float64, error) {
return strconv.ParseFloat(c.Input().Get(key), 64)
}
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)
}
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)
if err != nil {
return err
}
defer f.Close()
io.Copy(f, file)
return nil
}
2013-05-07 07:36:43 +00:00
func (c *Controller) StartSession() session.SessionStore {
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
}
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)
}
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)
}
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
2013-08-10 15:58:25 +00:00
func (c *Controller) DestroySession() {
GlobalSessions.SessionDestroy(c.Ctx.ResponseWriter, c.Ctx.Request)
}
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
func (c *Controller) GetSecureCookie(Secret, key string) (string, bool) {
val := c.Ctx.GetCookie(key)
if val == "" {
return "", false
}
parts := strings.SplitN(val, "|", 3)
2013-09-26 13:06:37 +00:00
if len(parts) != 3 {
return "", false
}
vs := parts[0]
timestamp := parts[1]
sig := parts[2]
h := hmac.New(sha1.New, []byte(Secret))
fmt.Fprintf(h, "%s%s", vs, timestamp)
if fmt.Sprintf("%02x", h.Sum(nil)) != sig {
return "", false
}
2013-09-28 13:36:36 +00:00
res, _ := base64.URLEncoding.DecodeString(vs)
return string(res), true
}
2013-09-28 13:36:36 +00:00
func (c *Controller) SetSecureCookie(Secret, name, val string, age int64) {
vs := base64.URLEncoding.EncodeToString([]byte(val))
timestamp := strconv.FormatInt(time.Now().UnixNano(), 10)
h := hmac.New(sha1.New, []byte(Secret))
fmt.Fprintf(h, "%s%s", vs, timestamp)
sig := fmt.Sprintf("%02x", h.Sum(nil))
cookie := strings.Join([]string{vs, timestamp, sig}, "|")
c.Ctx.SetCookie(name, cookie, age, "/")
}
2013-07-08 08:17:08 +00:00
func (c *Controller) XsrfToken() string {
if c._xsrf_token == "" {
token, ok := c.GetSecureCookie(XSRFKEY, "_xsrf")
if !ok {
2013-09-28 13:36:36 +00:00
var expire int64
2013-08-07 03:22:23 +00:00
if c.XSRFExpire > 0 {
2013-09-28 13:36:36 +00:00
expire = int64(c.XSRFExpire)
2013-08-07 03:22:23 +00:00
} else {
2013-09-28 13:36:36 +00:00
expire = int64(XSRFExpire)
2013-08-07 03:22:23 +00:00
}
token = GetRandomString(15)
c.SetSecureCookie(XSRFKEY, "_xsrf", token, expire)
2013-07-08 08:17:08 +00:00
}
c._xsrf_token = token
}
return c._xsrf_token
}
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")
2013-09-22 06:35:01 +00:00
} else if c._xsrf_token != token {
2013-07-08 08:17:08 +00:00
c.Ctx.Abort(403, "XSRF cookie does not match POST argument")
}
return true
}
func (c *Controller) XsrfFormHtml() string {
return "<input type=\"hidden\" name=\"_xsrf\" value=\"" +
2013-09-28 14:22:54 +00:00
c._xsrf_token + "\"/>"
2013-07-08 08:17:08 +00:00
}
func (c *Controller) GoToFunc(funcname string) {
if funcname[0] < 65 || funcname[0] > 90 {
panic("GoToFunc should exported function")
}
c.gotofunc = funcname
}