Created
December 2, 2019 20:29
-
-
Save seanpianka/376d578f440032b9e11e69c1c79667a4 to your computer and use it in GitHub Desktop.
Database session middleware for Golang Echo API
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
const ( | |
DatabaseConfigFile = "database.json" | |
DatabaseDriver = "mysql" | |
DatabaseKey = "db" | |
) | |
type DatabaseConfig struct { | |
Driver struct { | |
Database string `json:"dbname"` | |
Host string `json:"host"` | |
Port string `json:"port"` | |
User string `json:"user"` | |
Pass string `json:"pass"` | |
} `json:"mysql"` | |
} | |
func LoadDatabaseConfiguration(file string) DatabaseConfig { | |
var config DatabaseConfig | |
configFile, err := os.Open(file) | |
defer func() { | |
err := configFile.Close() | |
if err != nil { | |
panic(err) | |
} | |
}() | |
if err != nil { | |
log.Println(err.Error()) | |
} | |
jsonParser := json.NewDecoder(configFile) | |
if err = jsonParser.Decode(&config); err != nil { | |
panic(err) | |
} | |
return config | |
} | |
func CreateBoundedDatabaseConnection(configPath string) echo.MiddlewareFunc { | |
config := LoadDatabaseConfiguration(configPath) | |
databaseUri := fmt.Sprintf( | |
"%s:%s@tcp(%s:%s)/%s?parseTime=true", | |
config.Driver.User, | |
config.Driver.Pass, | |
config.Driver.Host, | |
config.Driver.Port, | |
config.Driver.Database, | |
) | |
return func(next echo.HandlerFunc) echo.HandlerFunc { | |
return func(c echo.Context) error { | |
db, err := sql.Open(DatabaseDriver, databaseUri) | |
if err != nil { | |
panic(err) | |
} | |
c.Set(DatabaseKey, db) | |
c.Response().After(func() { | |
db := c.Get(DatabaseKey).(*sql.DB) | |
err := db.Close() | |
if err != nil { | |
panic(err) | |
} | |
}) | |
return next(c) | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment