-1

I continue to get this issue and I do not understand why package models

import (
"database/sql"
"fmt"

_ "github.com/lib/pq"
)

const (
 host     = "localhost"
 port     = 5432
 user     = "postgres"
 password = "postgres"
 dbname   = "postgres"
 )

  var db *sql.DB

  func InitDB() {
   psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+
   "password=%s dbname=%s sslmode=disable",
   host, port, user, password, dbname)
 db, err := sql.Open("postgres", psqlInfo)
 if err != nil {
   panic(err)
 }
 defer db.Close()

 err = db.Ping()
 if err != nil {
   panic(err)
 }

 fmt.Println("Successfully connected!")
  }

Apologies as I am new to go and attemping to understand it. Thank you for any help. I have attempted to pull the library as well as move it around

Vadim Kotov
  • 8,084
  • 8
  • 48
  • 62

1 Answers1

1

Assuming you're referring to

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

This is importing for a side effect. The underscore is in the alias position. This allows you to circumvent the error (or automatic removal if using something like goimports) of an unused import.

When github.com/lib/pq is imported it runs an init() function that registers the postgres database driver.

This init function can be seen here https://github.com/lib/pq/blob/d34b9ff171c21ad295489235aec8b6626023cd04/conn.go#L48-L50

func init() {
    sql.Register("postgres", &Driver{})
}

If you needed to refer to something in the pq package itself it is fine to remove the underscore and then make direct reference to the package. However, make sure you do not unintentionally remove the import entirely or your attempt to open a connection to the postgres database will fail.

Thomas
  • 3,603
  • 1
  • 18
  • 23