I'm trying to create postgresql database struct to automate the system in Golang.
This code is working;
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func checkError(err error){
if err!=nil{
panic(err)
}
}
const (
host = "localhost"
port = 5432
user = "postgres"
password = "123"
dbname = "DatabaseName"
)
func main() {
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)
checkError(err)
err = db.Ping()
checkError(err)
defer db.Close()
fmt.Println("Successfully connected!")
}
Result: Successfully connected!
But When I'm trying to create a struct the system giving me an error;
package main
import (
"database/sql"
"fmt"
_ "github.com/lib/pq"
)
func checkError(err error){
if err!=nil{
panic(err)
}
}
type Database struct{
host, port, user, password, dbname string
db *sql.DB
}
func(d *Database) Open(){
psqlInfo := fmt.Sprintf("host=%s port=%d user=%s "+"password=%s dbname=%s sslmode=disable", d.host, d.port, d.user, d.password, d.dbname)
db, err := sql.Open("postgres", psqlInfo)
checkError(err)
d.db = db
}
func(d *Database) IsOpened() {
checkError(d.db.Ping())
}
func main() {
a := Database{host: "localhost", port: "5432", user: "postgres", password: "123", dbname: "DatabaseName"}
a.Open()
a.IsOpened()
}
Result: panic: dial tcp: lookup tcp/%!d(string=5432): getaddrinfow: The specified class could not be found.
goroutine 1 [running]: main.checkError(...) /main.go:11
main.(*Database).IsOpened(...) /main.go:28 main.main() /main.go:34 +0xcc