Home  >  Article  >  Backend Development  >  How to Fix \"x509: certificate is valid for ...\" Error Connecting to Cloud SQL with SSL and Golang?

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

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-10-23 19:47:02818browse

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

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>

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!

Statement:
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