How to use gorm with Beego

Beego ORM is not yet complete (for example, it does not support foreign key restrictions). So I decided to use gorm with Beego. What is the right way to do this? I saw a sample code from gorm:

import (
    "github.com/jinzhu/gorm"
    _ "github.com/jinzhu/gorm/dialects/postgres"
)

func main() {
  db, err := gorm.Open("postgres", "host=myhost user=gorm dbname=gorm sslmode=disable password=mypassword")
  defer db.Close()
}

But is it necessary to connect to the database every time in each function of the controller? Is there a way to use something like long joins for polling?

+4
source share
2 answers

gorm uses the sql.DB type built into gorm.DB under the hood, which

DB - , . goroutines. sql ; .

, DB , ,

tr:=db.Begin()
+3

, @Uvelichitel, , db (, ).

, , db:

// appname/conn.go

package db

import (
  "github.com/jinzhu/gorm"
  ...
)

var (
  // this one gonna contain an open connection
  // make sure to call Connect() before using it
  Conn *gorm.DB
)

func Connect(dbConnString string) (*gorm.DB, error) {
  db, err := gorm.Open("postgres", dbConnString)
  Conn = db
  return db, err
}

db.Connect main.go db.Conn ( , ).

import "appname/db"

func main() {
  conn, _ := db.Connect("host=localhost user=postgres ...")
  // db.Conn is initialized and ready for usage anywhere else

main.go, .

+1

Source: https://habr.com/ru/post/1653963/


All Articles