Search code examples
gorevelgo-gorm

How can I switch database connection and share it to model in Golang? (Revel + Gorm)


I want to setup Database sharding like https://github.com/thiagopradi/octopus in Revel + Gorm(or any other ORM in Golang).

I will get db connection string in security filter (which was a custom filter, added after revel's param filter). Now I need to switch db connection in next custom filter called db filter

And also need to implement db connection pool in revel application start up.


Solution

  • First is prepare you DB connection on the init (only call once) :

    db1, err := gorm.Open(dbdriver, dboption) //your main server
    db2, err := gorm.Open(dbdriver, dboption) //your sharding 1
    db3, err := gorm.Open(dbdriver, dboption) //your sharding 2
    

    And on your db filter just choose the between db1, db2, or db3 you want to be used by your model. Thats all.

    Gorm already make the pool for you, so you don't need to take care.