Skip to content

Beego数据库与日志操作

Orm操作查询与修改范例

  • DDL
    CREATE TABLE `page` (
    `id` int(11) unsigned NOT NULL AUTO_INCREMENT,
    `website` varchar(225) NOT NULL DEFAULT '',
    `email` varchar(255) NOT NULL DEFAULT '',
    PRIMARY KEY (`id`)
    ) ENGINE=InnoDB DEFAULT CHARSET=utf8;
    
  • controllers/default.go

    package controllers
    
    import (
        "cms/models"
        beego "github.com/beego/beego/v2/server/web"
    )
    
    type MainController struct {
        beego.Controller
    }
    
    func (c *MainController) Get() {
        //c.Data["Website"] = "beego.vip"
        //c.Data["Email"] = "astaxie@gmail.com"
        models.UpdatePage()
        obj := models.GetPage()
        c.Data["Website"] = obj.Website
        c.Data["Email"] = obj.Email
        c.TplName = "index.tpl"
    }
    

  • models/page.go

    package models
    
    import (
        "fmt"
        "github.com/beego/beego/v2/client/orm"
        _ "github.com/go-sql-driver/mysql"
    )
    
    type Page struct {
        Id      int
        Website string
        Email   string
    }
    
    func init() {
        orm.RegisterDataBase("default", "mysql", "root:root@tcp(127.0.0.1:3306)/page?charset=utf8")
        orm.RegisterModel(new(Page))
        //orm.RunSyncdb("default", false, true)
    }
    
    func GetPage() Page {
        //res := Page{Website: "弹力笔记", Email: "admin@elasticnotes.com"}
        //return res
        o := orm.NewOrm()
        p := Page{Id: 1}
        err := o.Read(&p)
        if err != nil {
            fmt.Println(err)
        }
        return p
    }
    
    // 修改
    func UpdatePage() {
        p := Page{Id: 1, Website: "佳能", Email: "修改了email"}
        o := orm.NewOrm()
        o.Update(&p) // p中不存在的column会被置空
        //o.Update(&p, "Email") // 只想修改某个字段
    }
    

Session 与 Log 实践

Session 相关

  • config/app.conf

    1
    2
    3
    4
    ······
    # beego 开启Session
    sessionon = true
    ······
    

  • 设置Session 获取 Session

    package controllers
    
    import (
        beego "github.com/beego/beego/v2/server/web"
    )
    
    type MainController struct {
        beego.Controller
    }
    
    func (c *MainController) Get() {
        c.SetSession("UserName", "elasticnotes")
        c.GetSession("UserName")
    }
    

Log 相关

package main

import (
    _ "cms/routers"
    "github.com/astaxie/beego/logs"
    beego "github.com/beego/beego/v2/server/web"
)

func main() {
    // 设置日志级别
    logs.SetLevel(beego.LevelInformational)
    // 日志存储形式与存储目录地址
    logs.SetLogger("file", `{"filename": "logs/test.log"}`)
    beego.Run()
}