How to Fix \'x509: certificate is valid for ...\' Error Connecting to Cloud SQL with SSL and Golang?

Mary-Kate Olsen
Release: 2024-10-23 19:47:02
Original
817 people have browsed it

How to Fix

Connecting to Google Cloud SQL with SSL and Golang from Google App Engine

Connecting to Google Cloud SQL using Golang and the go-sql-driver can encounter errors when using SSL. One specific error that may arise is:

x509: certificate is valid for projectName:instanceName, not projectName
Copy after login

To resolve this issue, it is crucial to set the ServerName property when registering a custom TLSConfig with the MySQL driver, in addition to specifying the project-id:instance-name within sql.Open().

Here's an example that demonstrates this fix:

<code class="go">import "database/sql"
import _ "github.com/go-sql-driver/mysql"

// Create a custom TLS configuration.
tlsConfig := &tls.Config{
    RootCAs:      rootCertPool,
    Certificates: clientCert,
    ServerName:   "projectName:instanceName",
}

// Register the TLS configuration with the MySQL driver.
mysql.RegisterTLSConfig("custom", tlsConfig)

// Establish the database connection with SSL enabled.
db, err := sql.Open("mysql", "user@cloudsql(project-id:instance-name)/dbname?tls=custom")</code>
Copy after login

By appending ?tls=nameOfYourCustomTLSConfig to the connection string, you can specify the custom TLS configuration to be used. This ensures that the connection is established correctly with SSL.

The above is the detailed content of How to Fix \'x509: certificate is valid for ...\' Error Connecting to Cloud SQL with SSL and Golang?. For more information, please follow other related articles on the PHP Chinese website!

source:php
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
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!