首页  >  文章  >  后端开发  >  如何修复使用 SSL 和 Golang 连接到 Cloud SQL 时出现的“x509:证书对...有效”错误?

如何修复使用 SSL 和 Golang 连接到 Cloud SQL 时出现的“x509:证书对...有效”错误?

Mary-Kate Olsen
Mary-Kate Olsen原创
2024-10-23 19:47:02825浏览

How to Fix

使用 SSL 和 Golang 从 Google App Engine 连接到 Google Cloud SQL

使用 Golang 和 go-sql 连接到 Google Cloud SQL-使用 SSL 时驱动程序可能会遇到错误。可能出现的一个具体错误是:

x509: certificate is valid for projectName:instanceName, not projectName

要解决此问题,除了指定 project-id:instance 之外,在使用 MySQL 驱动程序注册自定义 TLSConfig 时设置 ServerName 属性也至关重要-name inside sql.Open().

以下示例演示了此修复:

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

通过将 ?tls=nameOfYourCustomTLSConfig 附加到连接字符串,您可以指定自定义 TLS 配置被使用。这可确保使用 SSL 正确建立连接。

以上是如何修复使用 SSL 和 Golang 连接到 Cloud SQL 时出现的“x509:证书对...有效”错误?的详细内容。更多信息请关注PHP中文网其他相关文章!

声明:
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn