How to connect to remove server

I uploaded my golang files into the server (for example 125.168.147.11) and I also put my postgres onto the server, but now I do not how to connect to the postgres from my golang, I did something like this

const (
host     = "http://125.168.147.11"
port     = 5432
user     = "postgres"
password = "postgres"
dbname   = "postgres"
)

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()

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

fmt.Println("Successfully connected!")

}

but I got an error

panic: dial tcp 78.140.223.85:5432: connect: connection refused

‘localhost’ is a hostname that will resolve to ‘127.0.0.1’, which is the IP given to the a ‘loopback’ interface that will always be local host machine.

If the postgres server is on the same machine as the Go program you should connect to ‘localhost’ without ‘http://’. PostgresSQL does not speak the HTTP protocol.

You should also take a look at https://www.khanacademy.org/computing/computer-science/internet-intro/internet-works-intro/v/the-internet-ip-addresses-and-dns to learn how IP-addresses and the Domain Name System (DNS) works, as your question is not about Go :slight_smile:

2 Likes

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.