W3Cschool
恭喜您成為首批注冊用戶
獲得88經(jīng)驗值獎勵
我們經(jīng)常需要獲取用戶傳遞的數(shù)據(jù),包括 Get、POST 等方式的請求,beego 里面會自動解析這些數(shù)據(jù),你可以通過如下方式獲取數(shù)據(jù):
使用例子如下:
func (this *MainController) Post() {
jsoninfo := this.GetString("jsoninfo")
if jsoninfo == "" {
this.Ctx.WriteString("jsoninfo is empty")
return
}
}
如果你需要的數(shù)據(jù)可能是其他類型的,例如是 int 類型而不是 int64,那么你需要這樣處理:
func (this *MainController) Post() {
id := this.Input().Get("id")
intid, err := strconv.Atoi(id)
}
更多其他的 request 的信息,用戶可以通過 this.Ctx.Request 獲取信息,關于該對象的屬性和方法參考手冊 Request。
如果要把表單里的內(nèi)容賦值到一個 struct 里,除了用上面的方法一個一個獲取再賦值外,beego 提供了通過另外一個更便捷的方式,就是通過 struct 的字段名或 tag 與表單字段對應直接解析到 struct。
定義 struct:
type user struct {
Id int `form:"-"`
Name interface{} `form:"username"`
Age int `form:"age"`
Email string
}
表單:
<form id="user">
名字:<input name="username" type="text" />
年齡:<input name="age" type="text" />
郵箱:<input name="Email" type="text" />
<input type="submit" value="提交" />
</form>
Controller 里解析:
func (this *MainController) Post() {
u := user{}
if err := this.ParseForm(&u); err != nil {
//handle error
}
}
注意:
在 API 的開發(fā)中,我們經(jīng)常會用到 JSON 或 XML 來作為數(shù)據(jù)交互的格式,如何在 beego 中獲取 Request Body 里的 JSON 或 XML 的數(shù)據(jù)呢?
func (this *ObjectController) Post() {
var ob models.Object
var err error
if err = json.Unmarshal(this.Ctx.Input.RequestBody, &ob); err == nil {
objectid := models.AddOne(ob)
this.Data["json"] = "{\"ObjectId\":\"" + objectid + "\"}"
} else {
this.Data["json"] = err.Error()
}
this.ServeJSON()
}
在 beego 中你可以很容易的處理文件上傳,就是別忘記在你的 form 表單中增加這個屬性 enctype="multipart/form-data",否則你的瀏覽器不會傳輸你的上傳文件。
文件上傳之后一般是放在系統(tǒng)的內(nèi)存里面,如果文件的 size 大于設置的緩存內(nèi)存大小,那么就放在臨時文件中,默認的緩存內(nèi)存是 64M,你可以通過如下來調(diào)整這個緩存內(nèi)存大小:
beego.MaxMemory = 1<<22
或者在配置文件中通過如下設置:
maxmemory = 1<<22
Beego 提供了兩個很方便的方法來處理文件上傳:
<form enctype="multipart/form-data" method="post">
<input type="file" name="uploadname" />
<input type="submit">
</form>
保存的代碼例子如下:
func (c *FormController) Post() {
f, h, err := c.GetFile("uploadname")
if err != nil {
log.Fatal("getfile err ", err)
}
defer f.Close()
c.SaveToFile("uploadname", "static/upload/" + h.Filename) // 保存位置在 static/upload, 沒有文件夾要先創(chuàng)建
}
支持從用戶請求中直接數(shù)據(jù) bind 到指定的對象,例如請求地址如下
?id=123&isok=true&ft=1.2&ol[0]=1&ol[1]=2&ul[]=str&ul[]=array&user.Name=astaxie
var id int
this.Ctx.Input.Bind(&id, "id") //id ==123
var isok bool
this.Ctx.Input.Bind(&isok, "isok") //isok ==true
var ft float64
this.Ctx.Input.Bind(&ft, "ft") //ft ==1.2
ol := make([]int, 0, 2)
this.Ctx.Input.Bind(&ol, "ol") //ol ==[1 2]
ul := make([]string, 0, 2)
this.Ctx.Input.Bind(&ul, "ul") //ul ==[str array]
user struct{Name}
this.Ctx.Input.Bind(&user, "user") //user =={Name:"astaxie"}
Copyright©2021 w3cschool編程獅|閩ICP備15016281號-3|閩公網(wǎng)安備35020302033924號
違法和不良信息舉報電話:173-0602-2364|舉報郵箱:jubao@eeedong.com
掃描二維碼
下載編程獅App
編程獅公眾號
聯(lián)系方式:
更多建議: