How to Implement Database Account Password Encryption in Configuration Files

In certain scenarios, database account passwords cannot be configured in plaintext within configuration files and must be encrypted. During the database connection, the encrypted fields in the configuration file need to be decrypted. This requirement can be achieved by customizing a Driver (for detailed information about Driver, please refer to the chapter: ORM - Interface). Taking mysql as an example, we can write our own Driver, wrap the mysql driver from the framework community components, and override its Open method. Code example:

  1. import (
  2. "database/sql"
  3. "github.com/gogf/gf/contrib/drivers/mysql/v2"
  4. "github.com/gogf/gf/v2/database/gdb"
  5. )
  6. type MyBizDriver struct {
  7. mysql.Driver
  8. }
  9. // Open creates and returns an underlying sql.DB object for mysql.
  10. // Note that it converts time.Time argument to local timezone in default.
  11. func (d *MyBizDriver) Open(config *gdb.ConfigNode) (db *sql.DB, err error) {
  12. config.User = d.decode(config.User)
  13. config.Pass = d.decode(config.Pass)
  14. return d.Driver.Open(config)
  15. }
  16. func (d *MyBizDriver) decode(s string) string {
  17. // Execute field decryption logic
  18. // ...
  19. return s
  20. }