go語言beego框架web開發(fā)語法筆記示例
兩個跳轉(zhuǎn)語法
第一個參數(shù)是請求路徑,第二個參數(shù)是http狀態(tài)碼。
c.Redirect("/login",400) //重定向 c.TplName = "login.html"
模型創(chuàng)建
設(shè)置主鍵 `pk`
設(shè)置自增 `auto`
注意:當(dāng)Field類型為int,int32,int64,uint,uint32,uint64時,可以設(shè)置字段為自增健,當(dāng)模型定義中沒有主鍵時,符合上述類型且名稱為Id的Field將視為自增健。
設(shè)置默認(rèn)值 `default(1111)`
設(shè)置長長度 `orm:size(100)`
設(shè)置允許為空 `null`,數(shù)據(jù)庫默認(rèn)是非空,設(shè)置null后可變成`ALLOW NULL`
設(shè)置唯一 `orm:"unique"`
設(shè)置浮點(diǎn)數(shù)精度 `orm:"digits(12);decimals(4)"` //總共12位,四位是小數(shù)
設(shè)置時間 `orm:"auto_now_add;type(datetime)"`
`orm:"auto_now;type(date)"`
注意:
auto_now 每次model保存時都會對時間自動更新
auto_now_add 第一次保存時才設(shè)置時間
設(shè)置時間的格式:type
# 案例 type User struct { beego.Controller Id int `orm:"pk;auto"` //主鍵且自增 Name string `orm:"size(20)"` //長度20 CreateTime time.Time Count int `orm:"defaule(0);null"` //默認(rèn)為0,可以為空 }
獲取post請求傳過來的值
獲取字符串
c.GetString("userName") //獲取字符串 func (c*MainController) AddAritcle() { c.Data["name"] = c.GetString("userName") c.Data["pwd"] = c.GetString("passwd") beego.Info("用戶名:",c.Data["name"]) beego.Info("密碼",c.Data["pwd"]) c.TplName = "success.html" }
獲取文件
f,h,err :=c.GetFile("file_name") //獲取文件 //f:文件句柄 //h:文件信息 //err:錯誤信息 defer f.Close() if err != nil{ beego.Info("上傳文件失敗") }else { c.SaveToFile("file_name","./staic/img/"+h.Filename) }
Html
就是別忘記在你的 form 表單中增加這個屬性 enctype="multipart/form-data",否則你的瀏覽器不會傳輸你的上傳文件。
<!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>登陸</title> </head> <body> <div> <div style="position:absolute;left:50%; top:50%;"> <form action="/addAritcle" method="post" enctype="multipart/form-data"> 用戶名:<input type="text" name="userName"> <p></p> 密碼:<input type="password" name="passwd"> <input type="file" name="uploadfilename"> <p></p> <input type="submit" value="注冊"> </form> </div> </div> </body> </html>
獲取文件后綴
fileext := path.Ext(h.Filename)
orm查詢表所有數(shù)據(jù)
var table_lis []models.User _,err := o.QueryTable("User").All(&table_lis) if err !=nil{ beego.Info("查詢文章出錯") return } beego.Info(table_lis)
前端循環(huán)語法
c.Data["table_lis"] = table_lis //業(yè)務(wù)邏輯傳過來的值 {{range .table_lis}} //循環(huán)訪問 <tr> <td>{{.Name}}</td> <td>{{.PassWord}}</td> </tr> {{end}}
前端格式化時間
<td>{{.time.Format "2006-01-02"}}</td> //格式化時間
前端url傳值方式
<td><a href="/addAritcle?id={{.Id}}" rel="external nofollow" ></a></td>
以上就是go語言beego框架web開發(fā)語法筆記示例的詳細(xì)內(nèi)容,更多關(guān)于go語言beego框架web開發(fā)語法的資料請關(guān)注腳本之家其它相關(guān)文章!
相關(guān)文章
golang利用函數(shù)閉包實(shí)現(xiàn)簡單的中間件
中間件設(shè)計(jì)模式是一種常見的軟件設(shè)計(jì)模式,它在許多編程語言和框架中被廣泛應(yīng)用,這篇文章主要為大家介紹一下golang利用函數(shù)閉包實(shí)現(xiàn)一個簡單的中間件,感興趣的可以了解下2023-10-10