snowpeak
snowpeak

Reputation: 867

How to separate DB connection initialization as a package in Go?

I have two packages, main and db. However, I get "DB declared and not used" error.

db.go

package db

import (
  "database/sql"
)

var DB *sql.DB

func Connect() {
  DB, err := sql.Open("mysql", "root:xxxx@/xxxx")
  if err != nil {
    panic(err.Error())
  }
}

func Close() {
  DB.Close()
}

main.go

package main

import (
    "database/sql"
    // "fmt"
    _ "github.com/go-sql-driver/mysql"
    "html/template"
    "net/http"
  "github.com/****/****/config"
  "github.com/****/****/db"
)

var tpl *template.Template

func init() {
    tpl = template.Must(template.ParseGlob("templates/*.gohtml"))
}

func main() {
    Connect()
    defer Close()
    loadRoutes()
    http.ListenAndServe(":8080", nil)
}

Upvotes: 2

Views: 5822

Answers (2)

Himanshu
Himanshu

Reputation: 12685

Golang is strict about variable declaration, it is also mentioned in the Golang FAQs:

The presence of an unused variable may indicate a bug, while unused imports just slow down compilation, an effect that can become substantial as a program accumulates code and programmers over time. For these reasons, Go refuses to compile programs with unused variables or imports, trading short-term convenience for long-term build speed and program clarity.

It's easy to address the situation, though. Use the blank identifier to let unused things persist while you're developing.

_, err := sql.Open("mysql", "root:Berlin2018@/jplatform")

But since you want db instance by creating a connection. I suggest to use it either by returning from the function OR You can check for the connection if it is working or not by sending ping to the database server as:

var DB *sql.DB

func Connect() {
    DB, err := sql.Open("mysql", "root:Berlin2018@/jplatform")
    if err = DB.Ping(); err != nil {
        log.Panic(err)
    }
}

Or you can create a struct which you can use anywhere you want including use of method receiver for every function which require db connection for querying the database as

type Env struct {
    db *sql.DB
}

func Connect() {
    db, err := sql.Open("mysql", "root:Berlin2018@/jplatform")
    _ = &Env{db: db}
}

func(env *Env) getDataFromDatabase(){}

Upvotes: 3

Raggaer
Raggaer

Reputation: 3318

You are not using your DB variable on db.go:

package db

import (
  "database/sql"
)

var DB *sql.DB

func Connect() {
  con, err := sql.Open("mysql", "root:Berlin2018@/jplatform")
  if err != nil {
    panic(err.Error())
  }
  DB = con
}

func Close() {
  DB.Close()
}

Upvotes: 1

Related Questions