简体   繁体   中英

GORM Cloud SQL Connection on App Engine Using Go

I'm trying to connect to a Cloud SQL database using GORM in golang.

db, _ = gorm.Open("mysql", "user:pass@cloudsql(connection:name:example)/")
if err != nil {
        log.Println(err)
        //panic(err)
    }

When I attempt to serve the app

goapp serve appengine/

I get a runtime error

ERROR    2017-02-19 20:48:05,436 http_runtime.py:396] bad runtime process port ['\r\n']

Which I found was related to the database migration

db.AutoMigrate(&models.Event{})

If I remove the AutoMigrate, the runtime process port error goes away. However whenever I access a route (ie /events) that does a database query, the connection gets dropped, a 404 page is thrown, and an error message is logged sql: database is closed

When I run the app locally by building the package go build && ./appname and using a local MySQL server, it works fine.

Can someone please tell me how to connect to a Cloud SQL database using Go's GORM framework and App Engine?

This is due to the call to log.New in this file: https://github.com/jinzhu/gorm/blob/master/logger.go#L15

This anwser explain why dev_appserver.py gets it: https://stackoverflow.com/a/24112953/4266494

To disable this, you can either disable all GORM logging:

db.LogMode(false)

Or use an adapter the logger output: https://github.com/benguild/GAEBridge/blob/master/log/debugLevel.go

db.SetLogger(NewDebugLogger(nil)) // on application scope
db.SetLogger(NewDebugLogger(appengine.NewContext(req))) // on request scope

I'm setting a new logger with the real context This is the only workaround I found to avoid crashes while keeping some logs, it could be awesome if one of you had a real one.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM