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

import (
	"bytes"
A
astaxie 已提交
5 6
	"compress/gzip"
	"compress/zlib"
A
#2  
astaxie 已提交
7 8
	"encoding/json"
	"encoding/xml"
A
session  
astaxie 已提交
9
	"github.com/astaxie/beego/session"
A
#2  
astaxie 已提交
10
	"html/template"
A
astaxie 已提交
11
	"io"
A
#2  
astaxie 已提交
12
	"io/ioutil"
A
astaxie 已提交
13
	"mime/multipart"
A
#2  
astaxie 已提交
14 15
	"net/http"
	"net/url"
A
astaxie 已提交
16
	"os"
A
#2  
astaxie 已提交
17 18
	"path"
	"strconv"
A
astaxie 已提交
19
	"strings"
A
#2  
astaxie 已提交
20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
)

type Controller struct {
	Ctx       *Context
	Data      map[interface{}]interface{}
	ChildName string
	TplNames  string
	Layout    string
	TplExt    string
}

type ControllerInterface interface {
	Init(ct *Context, cn string)
	Prepare()
	Get()
	Post()
	Delete()
	Put()
	Head()
	Patch()
	Options()
	Finish()
	Render() error
}

func (c *Controller) Init(ctx *Context, cn string) {
	c.Data = make(map[interface{}]interface{})
	c.Layout = ""
	c.TplNames = ""
	c.ChildName = cn
	c.Ctx = ctx
	c.TplExt = "tpl"

}

func (c *Controller) Prepare() {

}

func (c *Controller) Finish() {
}

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 {
A
astaxie 已提交
91 92 93 94 95
	rb, err := c.RenderBytes()

	if err != nil {
		return err
	} else {
A
astaxie 已提交
96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128
		c.Ctx.ResponseWriter.Header().Set("Content-Type", "text/html; charset=utf-8")
		output_writer := c.Ctx.ResponseWriter.(io.Writer)
		if EnableGzip == true && c.Ctx.Request.Header.Get("Accept-Encoding") != "" {
			splitted := strings.SplitN(c.Ctx.Request.Header.Get("Accept-Encoding"), ",", -1)
			encodings := make([]string, len(splitted))

			for i, val := range splitted {
				encodings[i] = strings.TrimSpace(val)
			}
			for _, val := range encodings {
				if val == "gzip" {
					c.Ctx.ResponseWriter.Header().Set("Content-Encoding", "gzip")
					output_writer, _ = gzip.NewWriterLevel(c.Ctx.ResponseWriter, gzip.BestSpeed)

					break
				} else if val == "deflate" {
					c.Ctx.ResponseWriter.Header().Set("Content-Encoding", "deflate")
					output_writer, _ = zlib.NewWriterLevel(c.Ctx.ResponseWriter, zlib.BestSpeed)
					break
				}
			}
		} else {
			c.Ctx.SetHeader("Content-Length", strconv.Itoa(len(rb)), true)
		}
		output_writer.Write(rb)
		switch output_writer.(type) {
		case *gzip.Writer:
			output_writer.(*gzip.Writer).Close()
		case *zlib.Writer:
			output_writer.(*zlib.Writer).Close()
		case io.WriteCloser:
			output_writer.(io.WriteCloser).Close()
		}
A
astaxie 已提交
129 130 131 132 133
		return nil
	}
	return nil
}

A
astaxie 已提交
134 135 136 137 138
func (c *Controller) RenderString() (string, error) {
	b, e := c.RenderBytes()
	return string(b), e
}

A
astaxie 已提交
139
func (c *Controller) RenderBytes() ([]byte, error) {
A
#2  
astaxie 已提交
140 141 142 143 144
	//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 == "" {
			c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt
		}
145
		if RunMode == "dev" {
A
astaxie 已提交
146
			BuildTemplate(ViewsPath)
147
		}
A
astaxie 已提交
148
		subdir := path.Dir(c.TplNames)
A
#2  
astaxie 已提交
149 150
		_, file := path.Split(c.TplNames)
		newbytes := bytes.NewBufferString("")
A
astaxie 已提交
151
		BeeTemplates[subdir].ExecuteTemplate(newbytes, file, c.Data)
A
#2  
astaxie 已提交
152 153 154
		tplcontent, _ := ioutil.ReadAll(newbytes)
		c.Data["LayoutContent"] = template.HTML(string(tplcontent))
		_, file = path.Split(c.Layout)
A
astaxie 已提交
155
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
156
		err := BeeTemplates[subdir].ExecuteTemplate(ibytes, file, c.Data)
A
#2  
astaxie 已提交
157 158 159
		if err != nil {
			Trace("template Execute err:", err)
		}
A
astaxie 已提交
160 161
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
162 163 164 165
	} else {
		if c.TplNames == "" {
			c.TplNames = c.ChildName + "/" + c.Ctx.Request.Method + "." + c.TplExt
		}
166
		if RunMode == "dev" {
A
astaxie 已提交
167
			BuildTemplate(ViewsPath)
168
		}
A
astaxie 已提交
169
		subdir := path.Dir(c.TplNames)
A
#2  
astaxie 已提交
170
		_, file := path.Split(c.TplNames)
A
astaxie 已提交
171
		ibytes := bytes.NewBufferString("")
A
astaxie 已提交
172
		err := BeeTemplates[subdir].ExecuteTemplate(ibytes, file, c.Data)
A
#2  
astaxie 已提交
173 174 175
		if err != nil {
			Trace("template Execute err:", err)
		}
A
astaxie 已提交
176 177
		icontent, _ := ioutil.ReadAll(ibytes)
		return icontent, nil
A
#2  
astaxie 已提交
178
	}
A
astaxie 已提交
179
	return []byte{}, nil
A
#2  
astaxie 已提交
180 181 182 183 184 185 186
}

func (c *Controller) Redirect(url string, code int) {
	c.Ctx.Redirect(code, url)
}

func (c *Controller) ServeJson() {
A
astaxie 已提交
187
	content, err := json.MarshalIndent(c.Data["json"], "", "  ")
A
#2  
astaxie 已提交
188 189 190 191 192 193 194 195 196 197
	if err != nil {
		http.Error(c.Ctx.ResponseWriter, err.Error(), http.StatusInternalServerError)
		return
	}
	c.Ctx.SetHeader("Content-Length", strconv.Itoa(len(content)), true)
	c.Ctx.ContentType("json")
	c.Ctx.ResponseWriter.Write(content)
}

func (c *Controller) ServeXml() {
A
astaxie 已提交
198
	content, err := xml.Marshal(c.Data["xml"])
A
#2  
astaxie 已提交
199 200 201 202 203 204 205 206 207 208
	if err != nil {
		http.Error(c.Ctx.ResponseWriter, err.Error(), http.StatusInternalServerError)
		return
	}
	c.Ctx.SetHeader("Content-Length", strconv.Itoa(len(content)), true)
	c.Ctx.ContentType("xml")
	c.Ctx.ResponseWriter.Write(content)
}

func (c *Controller) Input() url.Values {
209
	ct := c.Ctx.Request.Header.Get("Content-Type")
A
astaxie 已提交
210
	if strings.Contains(ct, "multipart/form-data") {
211 212 213 214
		c.Ctx.Request.ParseMultipartForm(MaxMemory) //64MB
	} else {
		c.Ctx.Request.ParseForm()
	}
A
#2  
astaxie 已提交
215 216
	return c.Ctx.Request.Form
}
X
xiemengjun 已提交
217

218 219 220 221 222 223 224 225 226 227 228 229
func (c *Controller) GetString(key string) string {
	return c.Input().Get(key)
}

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))
}

A
astaxie 已提交
230 231 232 233
func (c *Controller) GetFile(key string) (multipart.File, *multipart.FileHeader, error) {
	return c.Ctx.Request.FormFile(key)
}

A
astaxie 已提交
234 235 236 237 238 239 240 241 242 243 244 245 246 247 248
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
}

A
session  
astaxie 已提交
249
func (c *Controller) StartSession() (sess session.SessionStore) {
X
xiemengjun 已提交
250 251 252
	sess = GlobalSessions.SessionStart(c.Ctx.ResponseWriter, c.Ctx.Request)
	return
}
A
session  
astaxie 已提交
253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

func (c *Controller) SetSession(name string, value interface{}) {
	ss := c.StartSession()
	defer ss.SessionRelease()
	ss.Set(name, value)
}

func (c *Controller) GetSession(name string) interface{} {
	ss := c.StartSession()
	defer ss.SessionRelease()
	return ss.Get(name)
}

func (c *Controller) DelSession(name string) {
	ss := c.StartSession()
	defer ss.SessionRelease()
	ss.Delete(name)
}