Home > Article > Backend Development > How to Create a Singleton DB Instance with Methods in Go?
Creating a singleton with methods in Go can be achieved by utilizing an unexported implementing type and an exported interface.
Define an exported interface with the desired methods, such as:
<code class="go">package dbprovider type Manager interface { AddArticle(article *article.Article) error }</code>
Create an unexported type that implements the interface:
<code class="go">type manager struct { db *gorm.DB }</code>
Initialize the singleton instance in a package initialization function, which executes once before any package references:
<code class="go">var Mgr Manager func init() { db, err := gorm.Open("sqlite3", "../articles.db") if err != nil { log.Fatal("Failed to init db:", err) } Mgr = &manager{db: db} }</code>
Use the singleton instance by referring to the exported interface variable, e.g.:
<code class="go">if err := dbprovider.Mgr.AddArticle(someArticle); err != nil { // Handle error }</code>
To catch and return exceptions from gorm.Create(..):
<code class="go">func (mgr *manager) AddArticle(article *article.Article) (err error) { mgr.db.Create(article) if errs := mgr.db.GetErrors(); len(errs) > 0 { err = errs[0] } return }</code>
Instead of using a package initialization function, you can also initialize the singleton explicitly:
<code class="go">var mgr = newManager() func newManager() Manager { db, err := gorm.Open("sqlite3", "../articles.db") if err != nil { log.Fatal("Failed to init db:", err) } return &manager{db: db} }</code>
This approach allows users to decide whether to use the shared instance or create a new one, e.g. for testing purposes.
The above is the detailed content of How to Create a Singleton DB Instance with Methods in Go?. For more information, please follow other related articles on the PHP Chinese website!