config構造体&読み込み処理、DB接続処理を実装
This commit is contained in:
@@ -0,0 +1,39 @@
|
|||||||
|
type Config struct {
|
||||||
|
DB struct {
|
||||||
|
Type string `ini:"DBTYPE"`
|
||||||
|
Host string `ini:"DBHOST"`
|
||||||
|
Port int `ini:"DBPORT"`
|
||||||
|
User string `ini:"DBUSER"`
|
||||||
|
Password string `ini:"DBPASS"`
|
||||||
|
Name string `ini:"DBNAME"`
|
||||||
|
} `ini:"db"`
|
||||||
|
Server struct {
|
||||||
|
Host string `ini:"SERVERHOST"`
|
||||||
|
AllowOrigin string `ini:"ALLOWORIGIN"`
|
||||||
|
} `ini:"server"`
|
||||||
|
Security struct {
|
||||||
|
AISpamProtection bool `ini:"AI_SPAM_PROTECTION"`
|
||||||
|
AIProvider string `ini:"AI_PROVIDER"`
|
||||||
|
AIEndpoint string `ini:"AI_ENDPOINT"`
|
||||||
|
AIAPIKey string `ini:"AI_APIKEY"`
|
||||||
|
AISecretKey string `ini:"AI_SECRETKEY"`
|
||||||
|
AIModel string `ini:"AI_MODEL"`
|
||||||
|
AIInstructions string `ini:"AI_INSTURCTIONS"`
|
||||||
|
CaptchaEnabled bool `ini:"CAPTCHA_ENABLED"`
|
||||||
|
CaptchaType string `ini:"CAPTCHA_TYPE"`
|
||||||
|
CaptchaSiteKey string `ini:"CAPTCHA_SITEKEY"`
|
||||||
|
CaptchaSecretKey string `ini:"CAPTCHA_SECRETKEY"`
|
||||||
|
} `ini:"security"`
|
||||||
|
}
|
||||||
|
|
||||||
|
import "gopkg.in/ini.v1"
|
||||||
|
|
||||||
|
func LoadConfig(filePath string) (*Config, error) {
|
||||||
|
cfg, err := ini.Load(filePath)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
config := &Config{}
|
||||||
|
err = cfg.MapTo(config)
|
||||||
|
return config, err
|
||||||
|
}
|
||||||
@@ -0,0 +1,40 @@
|
|||||||
|
import (
|
||||||
|
"database/sql"
|
||||||
|
"fmt"
|
||||||
|
_ "github.com/go-sql-driver/mysql"
|
||||||
|
_ "github.com/mattn/go-sqlite3"
|
||||||
|
)
|
||||||
|
|
||||||
|
type Database struct {
|
||||||
|
*sql.DB
|
||||||
|
}
|
||||||
|
|
||||||
|
func NewDatabase(config *Config) (*Database, error) {
|
||||||
|
var dsn string
|
||||||
|
if config.DB.Type == "mysql" {
|
||||||
|
dsn = fmt.Sprintf("%s:%s@tcp(%s:%d)/%s?charset=utf8mb4&parseTime=True&loc=Local",
|
||||||
|
config.DB.User, config.DB.Password, config.DB.Host, config.DB.Port, config.DB.Name)
|
||||||
|
} else if config.DB.Type == "sqlite" {
|
||||||
|
dsn = config.DB.Name + ".db"
|
||||||
|
} else {
|
||||||
|
return nil, fmt.Errorf("unsupported database type: %s", config.DB.Type)
|
||||||
|
}
|
||||||
|
|
||||||
|
db, err := sql.Open(config.DB.Type, dsn)
|
||||||
|
if err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
if err := db.Ping(); err != nil {
|
||||||
|
return nil, err
|
||||||
|
}
|
||||||
|
|
||||||
|
db.SetMaxOpenConns(25)
|
||||||
|
db.SetMaxIdleConns(25)
|
||||||
|
|
||||||
|
return &Database{DB: db}, nil
|
||||||
|
}
|
||||||
|
|
||||||
|
func (d *Database) Close() error {
|
||||||
|
return d.DB.Close()
|
||||||
|
}
|
||||||
Reference in New Issue
Block a user