Home > Backend Development > Golang > How to Connect to a Postgres Database in Go When SSL is Disabled?

How to Connect to a Postgres Database in Go When SSL is Disabled?

Barbara Streisand
Release: 2024-12-05 10:41:10
Original
261 people have browsed it

How to Connect to a Postgres Database in Go When SSL is Disabled?

Connecting to Postgres with SSL Disabled

When attempting to connect to a Postgres database using Go, you may encounter the error "SSL is not enabled on the server." This error occurs when your code attempts to establish a connection with SSL encryption, but the server you're connecting to doesn't support SSL.

To resolve this issue, you need to establish a DB connection without SSL encryption. Here's how you can do it:

import (
    "database/sql"
    _ "github.com/lib/pq" // postgres driver
)

func main() {
    // Establish the connection without SSL encryption.
    db, err := sql.Open("postgres", "user=test password=test dbname=test sslmode=disable")
    if err != nil {
        fmt.Printf("Failed to open DB connection: %v", err)
        return
    }
    defer db.Close() // Remember to close the connection after use.

    // Prepare the statement without the SSL encryption.
    stmt, err := db.Prepare(selectStatement)
    if err != nil {
        fmt.Printf("Failed to prepare statement: %v", err)
        return
    }
    defer stmt.Close() // Remember to close the statement after use.
}
Copy after login

The above is the detailed content of How to Connect to a Postgres Database in Go When SSL is Disabled?. For more information, please follow other related articles on the PHP Chinese website!

source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template