My current project uses a database represented as object. Furthermore I want to implement methods like CreateUser()
, DeleteUser()
etc, but my current code requires the injection of the db-object as parameter in each function.
Making the db-object global would solve the problem, but I learnt that global variables are mostly seen as a bad practice. Are there any other solutions?
package main
import (
"fmt"
"time"
"github.com/jinzhu/gorm"
_ "github.com/lib/pq"
_ "github.com/mattn/go-sqlite3"
)
type User struct {
ID int
Name string `sql:"size:50"`
Username string `sql:"size:50"`
CreatedAt time.Time
UpdatedAt time.Time
}
func CreateUser(db gorm.DB, name, username string) {
user := User{
Name: name,
Username: username,
}
db.Create(&user)
}
func main() {
db, err := gorm.Open("sqlite3", "data.sqlite3")
if err != nil {
fmt.Println(err)
}
db.DB()
fmt.Println("Programm is running...")
CreateUser(db, "John Doe", "johndoe")
}