建立仓库
This commit is contained in:
55
model/common.go
Normal file
55
model/common.go
Normal file
@@ -0,0 +1,55 @@
|
||||
package model
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gorm.io/driver/mysql"
|
||||
"gorm.io/gorm"
|
||||
"os"
|
||||
"strconv"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func Init() {
|
||||
var err error
|
||||
|
||||
host := os.Getenv("MYSQL_HOST")
|
||||
if host == "" {
|
||||
host = "localhost"
|
||||
}
|
||||
|
||||
portStr := os.Getenv("MYSQL_PORT")
|
||||
var port int
|
||||
if portStr == "" {
|
||||
port = 3306
|
||||
} else {
|
||||
port, err = strconv.Atoi(portStr)
|
||||
if err != nil {
|
||||
panic(fmt.Sprintf("Invalid MYSQL_PORT environment variable: %s", portStr))
|
||||
}
|
||||
}
|
||||
|
||||
username := os.Getenv("MYSQL_USERNAME")
|
||||
if username == "" {
|
||||
panic("MYSQL_USERNAME environment variable is not set")
|
||||
}
|
||||
|
||||
password := os.Getenv("MYSQL_PASSWORD")
|
||||
if password == "" {
|
||||
panic("MYSQL_PASSWORD environment variable is not set")
|
||||
}
|
||||
|
||||
database := os.Getenv("MYSQL_DATABASE")
|
||||
if database == "" {
|
||||
panic("MYSQL_DATABASE environment variable is not set")
|
||||
}
|
||||
|
||||
dsn := fmt.Sprintf(
|
||||
"%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||
username, password, host, port, database,
|
||||
)
|
||||
DB, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user