You can use ApsaraDB for RDS instances to store data that is required by an application for a long period of time. This topic describes how to link a database to a Go application and verify the connection between the application and the database.

Environment variables

Web+ stores information about a database connection in environment variables for easy access. The following table lists the related environment variables.

Variable name Sample value Description
WP_RDS_ENGINE MySQL The database engine of the ApsaraDB for RDS instance.
WP_RDS_CONNECTION_ADDRESS rm-***.mysql.rds.aliyuncs.com The internal endpoint of the ApsaraDB for RDS instance.
WP_RDS_PORT 3306 The port number of the ApsaraDB for RDS instance.
WP_RDS_ACCOUNT_NAME webplus The account name of the ApsaraDB for RDS instance.
WP_RDS_ACCOUNT_PASSWORD ***** The password of the ApsaraDB for RDS instance.
WP_RDS_DATABASE webplus The ApsaraDB for RDS instance.

Install a database driver

Use the following command to install a database driver for MySQL.
go get github.com/go-sql-driver/mysql

Add a database

The following shows an example of how to add a database.

package main

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

func main() {
  user := os.Getenv("WP_RDS_ACCOUNT_NAME")
  passwd := os.Getenv("WP_RDS_ACCOUNT_PASSWORD")
  host := os.Getenv("WP_RDS_CONNECTION_ADDRESS")
  port := os.Getenv("WP_RDS_PORT")

  connStr := fmt.Sprintf("%s:%s@tcp(%s:%s)/? timeout=30s", user, passwd, host, port)
  db, _ := sql.Open("mysql", connStr)
  defer fd.Close()

  sqlTxt := "select 'OK' as result"
  rows, _ := db.Query(sqlTxt)
  var result string

  for rows.Next(){
    _ = rows.Scan(&result)
  }

  // output "OK"
  fmt.Println(result)
}

More information