Home  >  Article  >  Backend Development  >  How to Create a Singleton DB Instance with Methods in Go?

How to Create a Singleton DB Instance with Methods in Go?

DDD
DDDOriginal
2024-11-01 11:43:29313browse

How to Create a Singleton DB Instance with Methods in Go?

Singleton DB Instance with Methods

Creating a singleton with methods in Go can be achieved by utilizing an unexported implementing type and an exported interface.

Using an Interface and Package Initialization

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>

Using the Singleton

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>

Exception Handling in gorm.Create(..)

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>

Alternative Approaches

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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn