服务器处理程序中有多个数据库

时间:2020-08-05 09:57:29

标签: mongodb go

我正在遵循存储库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中的目录结构。我正在尝试为我的项目开发一个双数据库客户端,在那里我需要连接到Mongo和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))
}

0 个答案:

没有答案