GORM DB Connection on other package - go

I start learning Go, reading about pointers, and want to split my database connection , and handler function for API. Already tried myself, by following this solution , but when i trying to read data, i am having this error
[2018-06-26 21:59:45] sql: database is closed
this is my source code.
db.go
package db
import (
"fmt"
"github.com/jinzhu/gorm"
"github.com/joho/godotenv"
"os"
)
var Db *gorm.DB
func Open() error {
var err error
_ = godotenv.Load(".env")
dbType := os.Getenv("DB_TYPE")
dbConnString := os.Getenv("DB_CONN_STRING")
Db, err = gorm.Open(dbType, dbConnString)
if err != nil {
fmt.Println(err)
}
Db.LogMode(true)
defer Db.Close()
return err
}
func Close() error {
return Db.Close()
}
person.go
package model
import (
"github.com/jinzhu/gorm"
"github.com/gin-gonic/gin"
"fmt"
"namastra/gin/result"
"namastra/gin/db"
)
type Person struct {
gorm.Model
FirstName string `json:”firstname”`
LastName string `json:”lastname”`
}
/*var db *gorm.DB
var err error*/
func GetPeople(c *gin.Context) {
var people []result.Person
if err := db.Db.Select("ID,first_name,last_name").Find(&people).Error; err != nil {
c.AbortWithStatus(404)
fmt.Println(err)
} else {
c.JSON(200, people)
}
}
main.go
package main
import (
"log"
"namastra/gin/handler"
"namastra/gin/model"
"net/http"
"time"
"github.com/adam-hanna/jwt-auth/jwt"
"github.com/gin-gonic/gin"
_ "github.com/jinzhu/gorm/dialects/postgres"
"namastra/gin/db"
)
func main() {
if err := db.Open(); err != nil {
// handle error
panic(err)
}
defer db.Close()
router := gin.Default()
router.Use(gin.Recovery())
private := router.Group("/auth")
....(ommited)
router.GET("/", gin.WrapH(regularHandler))
router.GET("/people/", model.GetPeople)
router.Run("127.0.0.1:3000")
}
Sorry for my bad english, any kind of help is appreciated.
thank you.
edit1: case closed.
solution is by removing
defer Db.Close()
from db.go.
edi2: update some knowledge i learn by working in go project

As start learning GO, usually we put everything on single main.go file, and we think to split the code to multiple files.
That is the time Dependency Injection comes to play.
we can create something like this Env to store the handler.
type Env struct {
db *sql.DB
logger *log.Logger
templates *template.Template
}
and create something like this in 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
}
main.go files
package main
import (
"namastra/gin/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("/peoples", env.peoplesIndex)
http.ListenAndServe(":3000", nil)
}
func (env *Env) peoplesIndex(w http.ResponseWriter, r *http.Request) {
# ...
}
and in models/people.go
package models
import "database/sql"
type Book struct {
Isbn string
Title string
Author string
Price float32
}
func AllPeoples(db *sql.DB) ([]*People, error) {
rows, err := db.Query("SELECT * FROM peoples")
if err != nil {
return nil, err
}
defer rows.Close()
# ... ommited for simplicity
}
you can read the full code & explanation in Alex Edwards post

Related

how to create dinamic port in golang (echo framwork)

i have package config.go in this my code
package config
import (
"fmt"
logger "github.com/sirupsen/logrus"
"gorm.io/driver/postgres"
"gorm.io/gorm"
)
func DatabaseConnect() *gorm.DB {
DBURL := fmt.Sprintf("host=%s port=%s user=%s dbname=%s sslmode=disable password=%s", pkg.GodotEnv("DB_HOST"), pkg.GodotEnv("DB_PORT"), pkg.GodotEnv("DB_USER"), pkg.GodotEnv("DB_NAME"), pkg.GodotEnv("DB_PASSWORD"))
db, err := gorm.Open(postgres.Open(DBURL), &gorm.Config{})
if err != nil {
defer logger.Info("Database connection failed")
logger.Fatal(err)
return nil
}
return db
}
and main.go
func main() {
e := echo.New()
db := config.DatabaseConnect()
middleware.WebSecurityConfig(e)
routes.NewRoute(db, e)
e.Logger.Fatal(e.Start(":8080"))
}
I want to create a dynamic routing like the example below :
server.Initialize(os.Getenv("DB_DRIVER"), os.Getenv("DB_USER"), os.Getenv("DB_PASSWORD"), os.Getenv("DB_PORT"), os.Getenv("DB_HOST"), os.Getenv("DB_NAME"))
server.Run(":" + os.Getenv("PORT"))
how to create dinamic port server ? thanks
Check this out: https://github.com/joho/godotenv.
Add your application configuration to your .env file in the root of your project:
DB_DRIVER=mysql
DB_USER=root
...
Then in your Go app you can do something like:
package main
import (
"log"
"os"
"github.com/joho/godotenv"
)
func main() {
err := godotenv.Load()
if err != nil {
log.Fatal("Error loading .env file")
}
driver:= os.Getenv("DB_DRIVER")
user:= os.Getenv("DB_USER")
// todo
}

go build doesn't recognise methods

I try to setup a small Golang Microservice for users with Gin and Mongodb.
package main
import (
"context"
"fmt"
"github.com/wzslr321/artiver/entity"
"github.com/wzslr321/artiver/settings"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
"log"
"os"
"os/signal"
"syscall"
"time"
)
type application struct {
users *entity.UserCollection
}
var app *application
func init() {
initMongo()
}
func initMongo() {
oc := options.Client().ApplyURI(settings.MongodbSettings.Uri)
client, err := mongo.NewClient(oc)
if err != nil {
log.Fatalf("Error occured while initializing a new mongo client: %v", err)
}
ctx, cancel := context.WithTimeout(context.Background(), 15*time.Second)
defer cancel()
err = client.Connect(ctx)
if err != nil {
log.Fatalf("Errorr occurred while connecting to a client: %v", err)
}
defer func() {
if err = client.Disconnect(ctx); err != nil {
panic(err)
}
}()
log.Println("Successfully connected to the database!")
app = &application{
users: &entity.UserCollection{
C: client.Database("artiver").Collection("users"),
},
}
}
func main() {
router := app.InitRouter()
It doesn't show any errors in my IDE ( GoLand ), but when I try to build it I get an error:
# command-line-arguments
users/cmd/app/main.go:67:15: app.InitRouter undefined (type *application has no field or method InitRouter)
It it easily visible on the image above, that I do have access to such a method. It is defined in the same package.
package main
import (
"github.com/gin-gonic/gin"
cors "github.com/rs/cors/wrapper/gin"
"net/http"
)
func (app *application) InitRouter() *gin.Engine {
r := gin.New()
r.Use(gin.Recovery())
r.Use(cors.Default())
r.GET("/", func(ctx *gin.Context) {
ctx.String(http.StatusOK, "Hello World")
})
user := r.Group("/api/user")
{
user.POST("/add", app.CreateUser)
}
return r
}
I have no idea how am I supposed to fix it and what is done wrong. I'd appreciate any hint about what isn't done correctly.
Answer based on #mkopriva help in comments.
The issue was related to not running all needed .go files.
In my case, the solution was to build it this way in my Makefile:
go build -o $(path)users cmd/app/*
In similar cases, go run . most likely will do the job.

DB.Exec args always results in an error for my placeholder

I have an SQL script with a variable I want to set from Golang.
SET #foo_bar_invitation_id = ?;
SELECT #foo_bar_invitation_id;
I.e. I want to set ? to "foobar". My code:
package main
import (
"io/ioutil"
"log"
"database/sql"
_ "github.com/go-sql-driver/mysql"
)
type handler struct{ db *sql.DB }
func (h handler) runsql() (err error) {
sqlscript, err := ioutil.ReadFile("script.sql")
if err != nil {
return
}
_, err = h.db.Exec(string(sqlscript), "foobar")
if err != nil {
log.Println(err)
}
return
}
Always results in Error 1064: You have an error in your SQL syntax; check the manual that corresponds to your MySQL server version for the right syntax to use near 'SELECT #foo_bar_invitation_id' at line 2
I test via code generated by gotests:
import (
"database/sql"
"os"
"testing"
_ "github.com/go-sql-driver/mysql"
)
var db *sql.DB
func TestMain(m *testing.M) {
db, _ = sql.Open("mysql", os.Getenv("DSN"))
defer db.Close()
os.Exit(m.Run())
}
func Test_handler_runsql(t *testing.T) {
type fields struct {
db *sql.DB
}
tests := []struct {
name string
fields fields
wantErr bool
}{{
"Check ID can be set",
fields{db: db},
false,
}}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
h := handler{
db: tt.fields.db,
}
if err := h.runsql(); (err != nil) != tt.wantErr {
t.Errorf("handler.step2runsql() error = %v, wantErr %v", err, tt.wantErr)
}
})
}
}
My DSN connection string includes ?multiStatements=true&sql_mode=TRADITIONAL.
I'm hoping I just do not understand how DB.Exec args interpolation / placeholder works, but I am finding it difficult to find examples.
The answer was to set interpolate params to true. https://github.com/go-sql-driver/mysql#interpolateparams

Using a singleton database class with separate models and services packages

My question is similar to How to create singleton DB class in GoLang but I'm having trouble getting it to work with separate models and services packages.
project/lib/database/mysql.go:
package database
import (
"fmt"
_ "github.com/go-sql-driver/mysql"
"github.com/jinzhu/gorm"
)
type Manager struct {
*gorm.DB
}
var Mgr *Manager
func init() {
dsn := MysqlConnectionString("parseTime=true")
tablePrefix := "demo"
var err error
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return fmt.Sprintf("%v_%v", tablePrefix, defaultTableName)
}
db, err := gorm.Open("mysql", dsn)
if err != nil {
panic(err)
}
Mgr = &Manager{db}
}
project/lib/models/retailer_keys.go
package models
import (
"fmt"
"project/lib/database"
"time"
)
type RetailerKeysInterface interface {
RetailerKeys() ([]*RetailerKey, error)
}
type DB struct {
database.Manager
}
type RetailerKey struct {
Id int `json:"id"`
RetailerId int `json:"retailer_id"`
Key string `json:"key"`
Enabled *bool `json:"enabled"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
}
func (db *DB) RetailerKeys() ([]*RetailerKey, error) {
var keys []*RetailerKey
if err := db.Find(&keys).Error; err != nil {
return nil, err
}
return keys, nil
}
project/lib/services/retailer_keys.go
import (
"fmt"
"strings"
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
"github.com/aws/aws-sdk-go/service/apigateway"
"gopkg.in/volatiletech/null.v6"
"project/lib/models"
"project/lib/services/api_keys"
)
func GetKeys() ([]*models.RetailerKey, error) {
var q models.RetailerKeysInterface
keys, err := q.RetailerKeys()
if err != nil {
return nil, err
}
return keys, nil
}
func CreateKey(id int) (models.RetailerKey, error) {
...
}
Then be able to use it in my main package like:
package main
import (
"context"
"encoding/json"
// "reflect"
"fmt"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
_ "project/lib/config"
"project/lib/services"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
statusCode := 200
keys, err := services.GetKeys()
if err != nil {
statusCode = 400
}
body, _ := json.Marshal(keys)
return events.APIGatewayProxyResponse{
Body: string(body),
StatusCode: statusCode,
}, nil
}
...
I'd like to be able to embed the relevant subset of the Manager type in my models.
EDIT:
Edited the question/code based on feedback in comments.
This gives me an error: runtime error: invalid memory address or nil pointer dereference.
I was definitely misunderstanding interfaces in go. After going through A Tour of Go it started to become clearer how it all fits together.
This is that I ended up doing for anyone that is going through the same thing. I'll leave the original question up so you can see the differences.
project/lib/database/mysql.go:
package database
import (
"fmt"
"log"
_ "github.com/go-sql-driver/mysql" // Needed for gorm
"github.com/jinzhu/gorm"
)
var Manager *gorm.DB
func init() {
var err error
dsn := MysqlConnectionString("parseTime=true")
tablePrefix := "qcommerce"
gorm.DefaultTableNameHandler = func(db *gorm.DB, defaultTableName string) string {
return fmt.Sprintf("%v_%v", tablePrefix, defaultTableName)
}
Manager, err = gorm.Open("mysql", dsn)
if err != nil {
log.Fatal(err)
}
if err := Manager.DB().Ping(); err != nil {
log.Fatal(err)
}
}
project/lib/models/retailer_keys.go
package models
import (
"project/lib/database"
"time"
)
type QRetailerKeys interface {
Insert() error
Find() error
}
type RetailerKey struct {
ID int `json:"id"`
RetailerID int `json:"retailer_id"`
Retailer Retailer `json:"retailer"`
Key string `json:"key"`
Enabled bool `json:"enabled" gorm:"DEFAULT:true"`
CreatedAt *time.Time `json:"created_at"`
UpdatedAt *time.Time `json:"updated_at"`
}
// RetailerKeys returns a slice of all keys in table
func RetailerKeys() ([]*RetailerKey, error) {
var keys []*RetailerKey
if err := database.Manager.Find(&keys).Error; err != nil {
return nil, err
}
return keys, nil
}
func (r *RetailerKey) Find() error {
...
}
// Create a new key
func (r *RetailerKey) Create() error {
return database.Manager.Create(&r).Error
}
project/lib/services/retailer_keys.go
package services
import (
"github.com/aws/aws-sdk-go/aws"
"github.com/aws/aws-sdk-go/aws/session"
// "github.com/aws/aws-sdk-go/service/apigateway"
"partners.drinks.com/lib/models"
"partners.drinks.com/lib/services/api_keys"
)
func sessionBuilder() *session.Session {
config := &aws.Config{
Region: aws.String("us-west-2"),
}
session := session.Must(session.NewSession(config))
return session
}
func GetKeys() ([]*models.RetailerKey, error) {
keys, err := models.RetailerKeys()
if err != nil {
return nil, err
}
return keys, nil
}
func CreateKey(id int) (models.RetailerKey, error) {
apikeys := &api_keys.ApiKeyBuilder{}
base64Key := apikeys.GenUUID().GenKey().Base64
var key = models.RetailerKey{
RetailerID: id,
Key: base64Key,
Enabled: func(b bool)
}
if err := key.Create(); err != nil {
return models.RetailerKey{}, err
}
...
return key, nil
}
I use it like:
package main
import (
"context"
"encoding/json"
"github.com/aws/aws-lambda-go/events"
"github.com/aws/aws-lambda-go/lambda"
_ "partners.drinks.com/lib/config"
"partners.drinks.com/lib/services"
)
func Handler(ctx context.Context, request events.APIGatewayProxyRequest) (events.APIGatewayProxyResponse, error) {
statusCode := 200
keys, err := services.GetKeys()
if err != nil {
statusCode = 400
}
body, _ := json.Marshal(keys)
return events.APIGatewayProxyResponse{
Body: string(body),
StatusCode: statusCode,
}, nil
}
...
Thanks to #mkopriva for the linked resources in the comments.

Connection DB in 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)?
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\n", 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
}
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

Resources