• 设为首页
  • 点击收藏
  • 手机版
    手机扫一扫访问
    迪恩网络手机版
  • 关注官方公众号
    微信扫一扫关注
    迪恩网络公众号

[go]beego获取参数/返回参数

原作者: [db:作者] 来自: [db:来源] 收藏 邀请

获取数据并转为对应的类型

- ?id=111&id=122
c.GetInt("id")
int,111

- ?id=111&id=122
c.GetBool("id")
bool,false


- ?id=111&id=122
c.GetString("id")
string,"111"

- ?id=111&id=122
c.GetStrings("id")
[]string,[]string{"111", "122"}


- ?id=111&id=122
c.Input().Get("id")
string,"111"

解析表单

  • c.ParseForm 直接解析到 struct
type user struct {
    Id    int         `form:"-"`
    Name  interface{} `form:"name"`
    Age   int         `form:"age"`
    Email string
}

func (c *MainController) Post() {
    u := user{}
    c.ParseForm(&u)

    fmt.Printf("%T,%#v\n", u, u)
    c.Ctx.WriteString("hello")
}

解析Request Body

  • 获取 Request Body 里的内容
type user struct {
    Id    int         `json:"-"`
    Name  interface{} `json:"name"`
    Age   int         `json:"age"`
    Email string
}

func (c *MainController) Post() {
    var u user
    json.Unmarshal(c.Ctx.Input.RequestBody, &u)
    fmt.Printf("%T,%#v\n", u, u)
    c.Ctx.WriteString("hello")
}

上传文件

<form enctype="multipart/form-data" method="post" action="http://localhost:8080/">
    <input type="file" name="uploadname" />
    <input type="submit">
</form>

func (c *MainController) Post() {
    f, h, err := c.GetFile("uploadname")
    if err != nil {
        log.Fatal("getfile err ", err)
    }
    fmt.Printf("%T,%#v\n", f, f)
    defer f.Close()
    c.SaveToFile("uploadname", "static/upload/" + h.Filename) // 保存位置在 static/upload, 没有文件夹要先创建
    c.Ctx.WriteString("post")
}

后端返回数据到前端

  • 返回字符串
c.Ctx.WriteString("<h1>hello world</h1>")
  • 返回模板html
c.Data["name"] = "mm"
c.Data["age"] = 22
c.TplName = "user.html"

<body>
    <h1>user</h1>
    {{.name}}
    {{.age}}
</body>
  • 返回json
type user struct {
    Name  string    `json:"name"`
    Age   int       `json:"age"`
    Birth time.Time `json:"birth"`
}

func (u *UserController) Get() {
    var p1 = &user{
        Name:  "mm",
        Age:   22,
        Birth: time.Now(),
    }

    u.Data["json"] = p1
    u.ServeJSON()
}

鲜花

握手

雷人

路过

鸡蛋
该文章已有0人参与评论

请发表评论

全部评论

专题导读
上一篇:
go项目目录结构发布时间:2022-07-10
下一篇:
goCD用虚拟机快速增加一个新agent发布时间:2022-07-10
热门推荐
热门话题
阅读排行榜

扫描微信二维码

查看手机版网站

随时了解更新最新资讯

139-2527-9053

在线客服(服务时间 9:00~18:00)

在线QQ客服
地址:深圳市南山区西丽大学城创智工业园
电邮:jeky_zhao#qq.com
移动电话:139-2527-9053

Powered by 互联科技 X3.4© 2001-2213 极客世界.|Sitemap