Last active
May 15, 2023 10:51
Star
You must be signed in to star a gist
Go Example: Google CloudSQL with CloudSQL Proxy and GORM
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
package main | |
import ( | |
"github.com/jinzhu/gorm" | |
_ "database/sql" | |
_ "github.com/GoogleCloudPlatform/cloudsql-proxy/proxy/dialers/mysql" | |
) | |
// You can read more in this post: http://forecastcloudy.net/2016/06/28/using-google-cloud-sql-from-go-with-gorm-in-google-container-engine-and-google-compute-engine/ | |
func main() { | |
// Using cloudsql-proxy will help you avoid white listing IPs and handling SSL. | |
// In this case, it will also run inside your Go program and will not require | |
// an additional process or container. | |
// Connection String details: | |
// * user - the user created inside the DB. You can see more details on how to create it without password here: | |
// https://cloud.google.com/sql/docs/sql-proxy#flags | |
// * project-id - your project id | |
// * zone - your general zone (us-central1/us-west1/etc) | |
// * db-name - the name of the database instance as it appears in the console | |
var dbConnectionString = "user@cloudsql(project-id:zone:instance-name)/db-name?charset=utf8&parseTime=True&loc=UTC" | |
var db *gorm.DB | |
var err error | |
if db, err = gorm.Open("mysql", dbConnectionString); err != nil { | |
panic(err) | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
This is awesome. Thanks!