Сonnect golang server with PSQL through Docker?

To connect a Golang server with PostgreSQL (PSQL) through Docker, you can follow the steps outlined below:

1. Start by creating a new directory for your project and navigate to that directory in your terminal or command prompt.

2. Initialize a new Go module by running the command "go mod init <module_name>". This will create a go.mod file that will track your project's dependencies.

3. Next, you will need to set up a Docker container running PostgreSQL. You can do this by running the command "docker run --name postgres-container -e POSTGRES_PASSWORD=<password> -p 5432:5432 -d postgres". This will create a new Docker container with the name "postgres-container" and expose port 5432.

4. Install the necessary PostgreSQL driver for Golang. You can do this by running the command "go get github.com/lib/pq".

5. Now, you can proceed with writing your Golang server code. Import the required packages by adding the following lines to your main.go file:

   import (
       "database/sql"
       "fmt"
       "log"
       "net/http"
       _ "github.com/lib/pq"
   )

6. Inside your main function, create a connection string to connect to the PostgreSQL database. Update the connection string with the appropriate values for your setup (host, port, user, password, and database name). For example:

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

   connStr := fmt.Sprintf("host=%s port=%d user=%s password=%s dbname=%s sslmode=disable", host, port, user, password, dbname)

7. Use the connection string to open a new database connection. Then, defer closing the connection to ensure it gets closed before the program exits. For example:

   db, err := sql.Open("postgres", connStr)
   if err != nil {
       log.Fatal(err)
   }
   defer db.Close()

8. With the database connection established, you can now execute SQL queries or perform other database operations. For example, you can retrieve data from a table by executing a simple SELECT query:

   rows, err := db.Query("SELECT * FROM users")
   if err != nil {
       log.Fatal(err)
   }
   defer rows.Close()

   for rows.Next() {
       var id int
       var name string
       err := rows.Scan(&id, &name)
       if err != nil {
           log.Fatal(err)
       }
       fmt.Println(id, name)
   }

9. Finally, start your Golang server by using the "http.ListenAndServe()" function or any other method of your choice.

10. When you're ready to run your Golang server, execute the command "go run main.go" in your terminal or command prompt. Your Golang server should now be successfully connected to the PostgreSQL database through Docker.

Note: Make sure Docker is installed and running on your machine before trying to run the above commands. Also, make sure you have the necessary authorization to access the PostgreSQL instance (e.g., correct username and password).