71 lines
1.5 KiB
Go
71 lines
1.5 KiB
Go
package models
|
||
|
||
import (
|
||
"fmt"
|
||
"github.com/astaxie/beego"
|
||
"github.com/jinzhu/gorm"
|
||
_ "github.com/jinzhu/gorm"
|
||
_ "github.com/go-sql-driver/mysql"
|
||
_ "github.com/jinzhu/gorm/dialects/mysql"
|
||
"time"
|
||
)
|
||
|
||
var db = initDbConnect()
|
||
|
||
type Model struct {
|
||
ID uint `gorm:"primary_key" json:"id"`
|
||
CreatedAt time.Time `json:"created_at"`
|
||
UpdatedAt time.Time `json:"updated_at"`
|
||
DeletedAt *time.Time `sql:"index" json:"deleted_at"`
|
||
}
|
||
|
||
func init() {
|
||
//SetMaxOpenConns用于设置最大打开的连接数
|
||
//SetMaxIdleConns用于设置闲置的连接数
|
||
db.DB().SetMaxIdleConns(10)
|
||
db.DB().SetMaxOpenConns(100)
|
||
|
||
// 启用Logger,显示详细日志
|
||
db.LogMode(true)
|
||
|
||
// 自动迁移模式
|
||
db.AutoMigrate(&User{},
|
||
&Note{},
|
||
&Comment{},
|
||
&Message{},
|
||
)
|
||
|
||
var count int
|
||
if err := db.Model(&User{}).Count(&count).Error; err == nil && count == 0 {
|
||
//新增
|
||
db.Create(&User{Name: "admin",
|
||
//邮箱
|
||
Email: "admin@qq.com",
|
||
//密码
|
||
Pwd: "123123",
|
||
//头像地址
|
||
Avatar: "/static/images/info-img.png",
|
||
//角色 管理员
|
||
Role: 0,
|
||
})
|
||
}
|
||
|
||
}
|
||
|
||
func initDbConnect() *gorm.DB {
|
||
config := beego.AppConfig
|
||
openStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||
config.String("mysqluser"),
|
||
config.String("mysqlpass"),
|
||
config.String("mysqlurls"),
|
||
config.String("mysqlport"),
|
||
config.String("mysqldb"))
|
||
|
||
db, err := gorm.Open("mysql", openStr)
|
||
//存在错误,则程序退出,panic是类似于java的RuntimeException错误
|
||
if err != nil {
|
||
panic("failed to connect database")
|
||
}
|
||
return db
|
||
}
|