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)?

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

You can use global variables, but I don't suggest to do it. What happens in more complicated applications where database logic is spread over multiple packages? It's better to use dependency injection:

File: main.go

package main

import (
    "bookstore/models"
    "database/sql"
    "fmt"
    "log"
    "net/http"
)

type Env struct {
    db *sql.DB
}

func main() {
    db, err := models.NewDB("postgres://user:pass@localhost/bookstore")
    if err != nil {
        log.Panic(err)
    }
    env := &Env{db: db}

    http.HandleFunc("/books", env.booksIndex)
    http.ListenAndServe(":3000", nil)
}

func (env *Env) booksIndex(w http.ResponseWriter, r *http.Request) {
    if r.Method != "GET" {
        http.Error(w, http.StatusText(405), 405)
        return
    }
    bks, err := models.AllBooks(env.db)
    if err != nil {
        http.Error(w, http.StatusText(500), 500)
        return
    }
    for _, bk := range bks {
        fmt.Fprintf(w, "%s, %s, %s, £%.2f
", bk.Isbn, bk.Title, bk.Author, bk.Price)
    }
}

File: models/db.go

package models

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

func NewDB(dataSourceName string) (*sql.DB, error) {
    db, err := sql.Open("postgres", dataSourceName)
    if err != nil {
        return nil, err
    }
    if err = db.Ping(); err != nil {
        return nil, err
    }
    return db, nil
}