Q
Q
qwentry2021-07-07 14:58:06
go
qwentry, 2021-07-07 14:58:06

GoLang, connecting to the database - unexpected EOF what is the reason?

Essence of the question:
On Windows 10, everything works without problems, as soon as I transfer the entire folder to the MacBook and run it. then on startup it gives this "unexpected EOF" error.
What is the reason? The code is the same there and there, respectively, but it does not work on mac os, but everything is ok on Win 10.

package main

import (
  "database/sql"
  "fmt"

  _ "github.com/lib/pq"
)

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


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)
  if err != nil {
    panic(err)
  }
  defer db.Close()

    result, err := db.Exec("insert into Products (model, company, price) values ('iPhone 11 Pro Max', $1, $2)",
        "Apple", 82000)
    if err != nil{
        panic(err) //На это ругается
    }
    fmt.Println(result.RowsAffected())
}


panic: unexpected EOF
goroutine 1 [running]:
main.main()
        /Users/admin/Desktop/test/add.go:37 +0x358
exit status 2


Upd: the error was that the port was incorrectly specified in the code. Read more in the comments

Answer the question

In order to leave comments, you need to log in

1 answer(s)
E
Evgeny Mamonov, 2021-07-07
@qwentry

As a rule, such a situation indicates problems with connecting to the database, drivers (libraries).
The first thing to do is to set up connections:

db.SetConnMaxIdleTime(0)
db.SetConnMaxLifetime(0)
db.SetMaxIdleConns(10)
db.SetMaxOpenConns(10)

If it doesn't help, you need to make sure that the database is really listening to the specified host and port in the settings.
For PostgreSQL
psql -h 127.0.0.1 -p 5432 -U user_name  database_name

For MySQL
mysql -h 127.0.0.1 -P 3307 -u user_name -p database_name

It is very important that 127.0.0.1 is specified (for MySQL), otherwise it will still connect via socket despite the fact that localhost is specified.
If the settings are correct and the database responds, you should try to update the drivers (libraries) of the databases, perhaps the database itself.
I came across situations when a similar problem went away with an update.
It also makes sense to look at the base logs, the reason for the connection failure can be described in more detail there.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question