原生sql不太熟悉?又想要簡單做到CRUD嗎?
那就來看看這篇文章吧~手把手教你最整潔的Gorm開發
Gorm是什麼?
有想了解更多可以到Gorm官網去看看哦
安裝Gorm
# 這邊假設各位都已經做好mod init
# 新增gorm的套件
go get -u "gorm.io/gorm"
# 這邊demo以postgres為主所以這邊新增postgres的套件
go get -u "gorm.io/driver/postgres"
主要code
type DBINFO struct {
dbUser string
dbPassword string
dbHost string
dbName string
dbPort string
}
func (dbInfo DBINFO) setupDBInfo() *DBINFO {
err := godotenv.Load()
if err != nil {
log.Println("Failed to load env file")
}
dbInfo.dbUser = os.Getenv("DB_USER")
dbInfo.dbPassword = os.Getenv("DB_PASSWORD")
dbInfo.dbHost = os.Getenv("DB_HOST")
dbInfo.dbName = os.Getenv("DB_NAME")
dbInfo.dbPort = os.Getenv("DB_PORT")
return &dbInfo
}
func GetDB() *gorm.DB {
dbInfo := &DBINFO{}
dbInfo = dbInfo.setupDBInfo()
// sslmode=disable
dsn := fmt.Sprintf("host=%s user=%s password=%s dbname=%s port=%s TimeZone=Asia/Taipei",
dbInfo.dbHost, dbInfo.dbUser, dbInfo.dbPassword, dbInfo.dbName, dbInfo.dbPort)
db, err := gorm.Open(postgres.Open(dsn), &gorm.Config{
Logger: logger.Default.LogMode(logger.Info),
})
if err != nil {
log.Println("Failed to connect DB")
}
return db
}
func getMember(){
err = postgresDB.Where("email = ?", req.Email).First(&member).Error
if err != nil {
panic
}
}