dsbgltg159136540 2016-09-10 14:59
浏览 140

Golang中的连接数据库

Where i can put initialize files like languages, connection db etc. in mvc structur golang (beego,revel)?

I tried to use in controller but it isn't good.

Is a good solution would be create base controller and put here all init connection, languages etc? or is there some other way (better)?

  • 写回答

2条回答 默认 最新

  • dongsu1951 2016-09-10 20:40
    关注

    I always do some packega where i keep my enviroment variables.

    For example main.go

    package main
    
    import (
        "net/http"
         env "github.com/vardius/example/enviroment"
    )
    
    func main() {
        //some extra code here, http srever or something
        defer env.DB.Close()
    }
    

    end inside enviroment dir env.go

    package env
    
    import (
        "database/sql"
    
        _ "github.com/go-sql-driver/mysql"
    )
    
    var (
        DB     *sql.DB
    )
    
    func connectToDB(dbURL string) *sql.DB {
        conn, err := sql.Open("mysql", dbURL)
        //check for err
    
        return conn
    }
    
    func init() {
        DB = connectToDB("root:password@tcp(127.0.0.1:3306)/test")
    }
    

    this way you initialize once your DB and can use it in all parts of your app by injecting env

    Ofcourse this solution has some downsides. First, code is harder to ponder because the dependencies of a component are unclear. Second, testing these components is made more difficult, and running tests in parallel is near impossible. With global connections, tests that hit the same data in a backend service could not be run in parallel.

    There is a great article about a Dependency Injection with Go

    I hope you will find this helpfull

    评论

报告相同问题?

悬赏问题

  • ¥15 微信小程序协议怎么写
  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看