因此,在Go中设计MVC架构时,我遇到了这个问题.我在设置模块中创建了一个settings.go文件,其中包含:
package settings
import (
_ "github.com/lib/pq"
"database/sql"
)
func load_db() {
db, err := sql.Open("postgres", "user=postgres password=postgres dbname=test_db")
}
Run Code Online (Sandbox Code Playgroud)
这个想法是每当API请求进入MVC的视图时加载此db调用.我在这里遇到的问题是我该怎么做
举一个Python的例子,我使用BaseController来处理这个问题.我在任何地方继承BaseController并创建和关闭数据库会话.
你正试图像Go或Java一样编写Go.去不是.Go没有类,Go有类型.Go不使用继承,Go使用组合.
如果你想在每次调用另一个函数/方法时调用一些函数/方法,你可以显式地编写它:
func (th *BaseThing) Init() {
th.OpenDB()
// Your code here.
}
Run Code Online (Sandbox Code Playgroud)
如果您想要多个值来共享一个东西,您可以明确地设置它:
db := NewDB()
th := NewThing() // Or th := NewThing(db) depending
th.DB = db // on how you design your constructor.
Run Code Online (Sandbox Code Playgroud)
如果要共享此功能,请使用组合:
type MyThing struct {
BaseThing
// Other fields here.
}
func (th *MyThing) Foo() {
th.Init() // Same as th.BaseThing.Init(). Opens DB etc.
// Your code here.
}
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
217 次 |
最近记录: |