EDITED Solved:How should i create singleton DBManager class in GoLang.
I Referred few code sample of how to create go singleton but i wish to have methods in those and call them on their singleton reference. My Code is as follows
package dbprovider
import (
"github.com/jinzhu/gorm"
_"github.com/jinzhu/gorm/dialects/sqlite"
"rest/article"
"log"
)
type DBOperations interface {
AddArticle(article *article.Article)
}
type DBManager struct {
db *gorm.DB
isInitialized bool
}
var dbManagerInstance = new()
func GetDBManager() DBManager {
return dbManagerInstance
}
func new() DBManager {
localDbRef, err := gorm.Open("sqlite3", "../articles.db")
if (err != nil) {
panic("Error initializing db")
} else {
log.Print("DB Initialized successfully")
}
return DBManager{db:localDbRef, isInitialized:true}
}
func (dbManager DBManager) AddArticle(article article.Article) (err error) {
if (dbManager.isInitialized) {
tx := dbManager.db.Begin()
//dbManager.db.NewRecord(article)
//dbManager.db.Commit()
tx.NewRecord(article)
tx.Commit()
errs := dbManager.db.GetErrors()
if (len(errs) > 0) {
err = errs[0]
} else {
log.Print("No error in this transactions")
}
}
return
}
With new answer i have updated this question including answer. But i have few queries. How to cathc and return exception from gorm.Create(..)