控制器

request 数据获取

func (c *BMainController) Post() {
        // 获取字符串类型的数据
	name := c.GetStirng("字段名")

        // 获取数值类型的数据........Get数据类型()
        id,err := c.GetInt("字段名")


        // 获取文件
        f,h,err := c.GetFile("字段名")
        defer f.Close()  // 关闭文件句柄
        
        endName := path.Ext(fileName)  // 获取文件后缀
      . size := h.Size   // 字节数


        if err != nil{
            // 文件上传错误
            return
        } else{
            c.SaveToFile("文件名称","存放路径/" + h.FileName)
        }

        // 设置cookie
        c.Ctx.SetCookie("key","value",time)
        c.Ctx.GetCookie("key")

        // cookie失效
        c.Ctx.SetCookie("key","value",-1)
        
}

response 数据返回

重定向,不能传递数据,速度快,无需渲染

c.Redirect("路径",状态码(int))

返回html页面

c.data["a"] = "bbb"   // 模板取值{{ .a }}
c.TplName = "index.html"

返回字符串

c.Ctx.WriteString("hello world")

返回json数据

package index

import (
	"fmt"
	"github.com/astaxie/beego"
)

type BMainController struct {
	beego.Controller
}

type myStruct struct {
	Code int `json:"code"`
	Data interface{} `json:"data"`
	Errmsg string `json:"errmsg"`
}

func (c *BMainController) Get() {
	myMap := make(map[string]int,3)
	myMap["1"] = 3
	myMap["2"] = 33
	myMap["3"] = 333
	myMap["4"] = 3333
	myMap["5"] = 33333
	Mytruct := &myStruct{
		0,&myMap,"",
	}
	c.Data["json"] = Mytruct
	fmt.Println(c.Data["json"])
	c.ServeJSON()
}
posted @ 2021-10-19 15:02  河图s  阅读(67)  评论(0)    收藏  举报