在GO中设计MVC架构

So, while designing a MVC architecture in Go, I came across this issue. I created a settings.go file in settings module which contains this:

package settings

import (
    _ "github.com/lib/pq"
    "database/sql"
)

func load_db() {
    db, err := sql.Open("postgres", "user=postgres password=postgres dbname=test_db")
}

The idea is to load this db call everytime an API request comes in to the views of the MVC. The problem I'm facing here is how do I

  1. Load this function whenever a call to some controller class is done.
  2. Inherit the db variable to use it across the controller.

To give an example in Python, I use a BaseController that deals with this. I inherit the BaseController everywhere and that creates and closes the db session.

You're trying to write Go like it's Java or Python. Go is neither. Go doesn't have classes, Go has types. Go doesn't use inheritance, Go uses composition.

If you want some function/method to be called every time an another function/method is called, you explicitly code it:

func (th *BaseThing) Init() {
    th.OpenDB()
    // Your code here.
}

If you want multiple values to share a thing, you explicitly set it:

db := NewDB()
th := NewThing()  // Or th := NewThing(db) depending
th.DB = db        // on how you design your constructor.

If you want to share this functionality, use composition:

type MyThing struct {
    BaseThing
    // Other fields here.
}

func (th *MyThing) Foo() {
    th.Init() // Same as th.BaseThing.Init(). Opens DB etc.
    // Your code here.
}

an API request comes in to the views of the MVC

In an MVC architecture requests are dispatched to controllers, not views.

Load this function whenever a call to some controller class is done.

Classes are instantiated, not called and there are no classes in Go.

Inherit the db variable to use it across the controller.

There's no inheritance in Go.

You're opening a DB connection in a package called settings. This is probably not the best name for that package.

In general, you're trying to do python/ruby/php in Go. That's not gonna get you very far. Read the Go documentation and learn to think like a gopher ;)

I don't totally understand what you mean but, if you just want to share a db connection to all your handlers you'd do something like this:

var (
        db *sql.DB
)

func main() {
        db = newDb(DbConnection)

        // handlers here
}


func newDb(connection string) *sql.DB {
        db, err := sql.Open("postgres", connection)
        if err != nil {
                panic(err)
        }

        return db
}

and in a settings file you could have:

const (
DbConnection     = "user=postgres password=postgres dbname=test_db"
)

All of your handlers will have access to the connection on db. The sql library handles connection pooling automatically.