Search code examples
google-app-enginegogoogle-cloud-sql

Connecting to CloudSQL from App Engine (Second Generation CloudSQL) GO


Love the Stack, My first post out of complete frustration. Thanks for you comments!

  • Created App Engine Project
  • Created Second Generation MySQL Instance in my App Engine Project
  • Created Database in the MySQL Instance
  • In App Engine, I activate the --> Google Cloud Shell <--. ( I am working at a command prompt in my console.cloud.google.com)

I have copied this basic GO program to connect to my MySQL instance.

I build it and run it. go build mysqlexample.go ./mysqlexample

I have not been able to achieve a successful connection. You can see all the various connection strings that I have tried and to the right of them is the response I get.

I can connect from my local windows machine using mysql admin.

Help?

package main

import (
    "database/sql"
    _ "github.com/go-sql-driver/mysql"
    "log"
    )

func main() {

    const dbIP = "104.xxx.xx.x"
    const dbInstanceName =  "esp-1-dev:us-central1:espdev"
    const dbName = "servpro"
    const dbUserName = "root"
    const dbPassword = "xxxxxxx"

    const dbOpenString = dbUserName + ":" + dbPassword + "@/" + dbInstanceName + "/" + dbName  //GETS RESPONSE default addr for network 'AppEngine:Zone:Project' unknown
    //const dbOpenString = dbUserName + "@cloudsql(" + dbInstanceName + ")/" + dbName   //GETS RESPONSE  dial cloudsql: unknown network cloudsql
    //const dbOpenString = dbUserName + "@/"  //+ "?parseTime=true&loc=UTC"                 //GETS RESPONSE  getsockopt: connection refused
    //const dbOpenString = dbUserName + ":" + dbPassword + "@tcp(" + dbIP + ":3306)/" + dbName  //GETS RESPONSE  dial tcp 104.xxx.xxx.x:3306: getsockopt: connection timed out

    //  Got this from stack overflow.  GoDocs are not updated to reflect 2nd Gen databases.
    //  http://stackoverflow.com/questions/38890022/tls-requested-but-server-does-not-support-tls-error-with-google-cloud-sql-2nd
    //user:password@cloudsql(copiedPastedInstanceConnectionName)/d‌​atabaseName?charset=‌​charset&collation=co‌​llation&tls=tlsConfi‌​gName&parseTime=true
    //First Generation Connection String    
        //username:password@cloudsql(appID:CloudSQLInstance)/databasename?parseTime=true&loc=UTC

    db, err := sql.Open("mysql", dbOpenString);
    defer db.Close()

    log.Println("Attempting Ping of database....")

    err = db.Ping()

    if err != nil {
        log.Println("db.Ping() failed:  " + dbOpenString)
        log.Println(err)
    } else {
        log.Println("Success!")
    }

}

Solution

  • The following are the correct connection strings, but they differ depending on which version of App Engine you are connecting from.

    App Engine Standard:

    user:password@cloudsql(INSTANCE_CONNECTION_NAME)/dbname
    

    App Engine Flexible:

    user:password@unix(/cloudsql/INSTANCE_CONNECTION_NAME)/dbname