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

DDD
Release: 2024-11-01 11:43:29
Original
321 people have browsed it

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>
Copy after login

Create an unexported type that implements the interface:

<code class="go">type manager struct {
    db *gorm.DB
}</code>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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>
Copy after login

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!

source:php.cn
Statement of this Website
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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!