Я следую структуре каталогов в репозитории https://github.com/victorsteven/Go-JWT-Postgres-Mysql-Restful-API/blob/master/api/controllers/base.gohttps: //github.com/victorsteven/Go-JWT-Postgres-Mysql-Restful-API/blob/master /api/controllers/base.go. Я пытаюсь разработать двойной клиент БД для своего проекта, где мне нужно подключиться к серверам баз данных Mon go и MYSQL. Я внес некоторые изменения в код и просто хотел проверить, лучше ли это делать. Можем ли мы разместить в обработчике двойной клиент БД?
контроллеры пакетов
import (
"fmt"
"log"
"net/http"
"github.com/gorilla/mux"
"github.com/jinzhu/gorm"
_ "github.com/jinzhu/gorm/dialects/mysql" //mysql database driver
_ "github.com/jinzhu/gorm/dialects/postgres" //postgres database driver
_ "github.com/jinzhu/gorm/dialects/sqlite" // sqlite database driver
"github.com/victorsteven/fullstack/api/models"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"go.mongodb.org/mongo-driver/mongo/readpref"
)
type Server struct {
DB *gorm.DB
Router *mux.Router
MongoClient *mongo.Client
}
func (server *Server) Initialize(Dbdriver, DbUser, DbPassword, DbPort, DbHost, DbName string) {
var err error
mongoURL := "mongodb://localhost:27017"
client, err := mongo.NewClient(options.Client().ApplyURI(mongoURL))
ctx, _ := context.WithTimeout(context.Background(), 10*time.Second)
err = client.Connect(ctx)
// Ping MongoDB
ctx, _ = context.WithTimeout(context.Background(), 10*time.Second)
if err = client.Ping(ctx, readpref.Primary()); err != nil {
fmt.Println("could not ping to mongo db service: %v\n", err)
return
}
fmt.Println("connected to nosql database:", mongoURL)
server.MongoClient = client
if Dbdriver == "mysql" {
DBURL := fmt.Sprintf("%s:%s@tcp(%s:%s)/%s?charset=utf8&parseTime=True&loc=Local", DbUser, DbPassword, DbHost, DbPort, DbName)
server.DB, err = gorm.Open(Dbdriver, DBURL)
if err != nil {
fmt.Printf("Cannot connect to %s database", Dbdriver)
log.Fatal("This is the error:", err)
} else {
fmt.Printf("We are connected to the %s database", Dbdriver)
}
}
if Dbdriver == "postgres" {
DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", DbHost, DbPort, DbUser, DbName, DbPassword)
server.DB, err = gorm.Open(Dbdriver, DBURL)
if err != nil {
fmt.Printf("Cannot connect to %s database", Dbdriver)
log.Fatal("This is the error:", err)
} else {
fmt.Printf("We are connected to the %s database", Dbdriver)
}
}
if Dbdriver == "sqlite3" {
//DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", DbHost, DbPort, DbUser, DbName, DbPassword)
server.DB, err = gorm.Open(Dbdriver, DbName)
if err != nil {
fmt.Printf("Cannot connect to %s database\n", Dbdriver)
log.Fatal("This is the error:", err)
} else {
fmt.Printf("We are connected to the %s database\n", Dbdriver)
}
server.DB.Exec("PRAGMA foreign_keys = ON")
}
server.DB.Debug().AutoMigrate(&models.User{}, &models.Post{}) //database migration
server.Router = mux.NewRouter()
server.initializeRoutes()
}
func (server *Server) Run(addr string) {
fmt.Println("Listening to port 8080")
log.Fatal(http.ListenAndServe(addr, server.Router))
}