本章节学习下beego的登陆校验和分类的添加、删除。
controllers文件下添加category.go和login.go
category.go源码:
package controllers import ( "myapp/models" "github.com/astaxie/beego" ) type CategoryController struct { beego.Controller } func (this *CategoryController) Get() { // 检查是否有操作 op := this.Input().Get("op") switch op { case "add": name := this.Input().Get("name") if len(name) == 0 { break } err := models.AddCategory(name) if err != nil { beego.Error(err) } this.Redirect("/category", 302) return case "del": id := this.Input().Get("id") if len(id) == 0 { break } err := models.DeleteCategory(id) if err != nil { beego.Error(err) } this.Redirect("/category", 302) return } this.Data["isActive"] = "category" this.TplName = "category.html" this.Data["IsLogin"] = checkAccount(this.Ctx) var err error this.Data["Categories"], err = models.GetAllCategories() if err != nil { beego.Error(err) } }
login.go源码:
package controllers import ( "github.com/astaxie/beego" "github.com/astaxie/beego/context" ) type LoginController struct { beego.Controller } func (this *LoginController) Get() { // 判断是否为退出操作 if this.Input().Get("exit") == "true" { this.Ctx.SetCookie("uname", "", -1, "/") this.Ctx.SetCookie("pwd", "", -1, "/") this.Redirect("/", 302) return } this.TplName = "login.html" } func (this *LoginController) Post() { // 获取表单信息 uname := this.Input().Get("uname") pwd := this.Input().Get("pwd") autoLogin := this.Input().Get("autoLogin") == "on" // 验证用户名及密码 if uname == beego.AppConfig.String("adminName") && pwd == beego.AppConfig.String("adminPass") { maxAge := 0 if autoLogin { maxAge = 1<<31 - 1 } this.Ctx.SetCookie("uname", uname, maxAge, "/") this.Ctx.SetCookie("pwd", pwd, maxAge, "/") } this.Redirect("/", 302) return } func checkAccount(ctx *context.Context) bool { ck, err := ctx.Request.Cookie("uname") if err != nil { return false } uname := ck.Value ck, err = ctx.Request.Cookie("pwd") if err != nil { return false } pwd := ck.Value return uname == beego.AppConfig.String("adminName") && pwd == beego.AppConfig.String("adminPass") }
另外models下的models.go添加:
func AddCategory(name string) error { o := orm.NewOrm() cate := &Category{ Title: name, Created: time.Now(), TopicTime: time.Now(), } // 查询数据 qs := o.QueryTable("category") err := qs.Filter("title", name).One(cate) if err == nil { return err } // 插入数据 _, err = o.Insert(cate) if err != nil { return err } return nil } func DeleteCategory(id string) error { cid, err := strconv.ParseInt(id, 10, 64) if err != nil { return err } o := orm.NewOrm() cate := &Category{Id: cid} _, err = o.Delete(cate) return err } func GetAllCategories() ([]*Category, error) { o := orm.NewOrm() cates := make([]*Category, 0) qs := o.QueryTable("category") _, err := qs.All(&cates) return cates, err }
另外还要修改:
conf文件夹下的app.conf添加用户名和密码的配置设置,
routers文件夹下的router.go添加新的路由规格,
views文件夹下添加各类模板。
最后运行,bee run myapp。出来如下图:
github:https://github.com/yangsir/beego_study
原创文章,作者:ItWorker,如若转载,请注明出处:https://blog.ytso.com/98492.html