github.com/aavshr/aws-sdk-go@v1.41.3/example/service/rds/rdsutils/authentication/iam_authentication.go (about)

     1  //go:build example && skip
     2  // +build example,skip
     3  
     4  package main
     5  
     6  import (
     7  	"database/sql"
     8  	"database/sql/driver"
     9  	"fmt"
    10  	"log"
    11  	"os"
    12  
    13  	"github.com/aavshr/aws-sdk-go/aws"
    14  	"github.com/aavshr/aws-sdk-go/aws/credentials/stscreds"
    15  	"github.com/aavshr/aws-sdk-go/aws/session"
    16  	"github.com/aavshr/aws-sdk-go/service/rds/rdsutils"
    17  )
    18  
    19  type stubDriver struct{}
    20  
    21  func (sd stubDriver) Open(name string) (driver.Conn, error) {
    22  	return nil, nil
    23  }
    24  
    25  // Usage ./iam_authentication <region> <db user> <db name> <endpoint to database> <iam arn>
    26  func main() {
    27  	if len(os.Args) < 5 {
    28  		log.Println("USAGE ERROR: go run concatenateObjects.go <region> <endpoint to database> <iam arn>")
    29  		os.Exit(1)
    30  	}
    31  
    32  	awsRegion := os.Args[1]
    33  	dbUser := os.Args[2]
    34  	dbName := os.Args[3]
    35  	dbEndpoint := os.Args[4]
    36  	awsCreds := stscreds.NewCredentials(session.New(&aws.Config{Region: &awsRegion}), os.Args[5])
    37  	authToken, err := rdsutils.BuildAuthToken(dbEndpoint, awsRegion, dbUser, awsCreds)
    38  
    39  	// Create the MySQL DNS string for the DB connection
    40  	// user:password@protocol(endpoint)/dbname?<params>
    41  	dnsStr := fmt.Sprintf("%s:%s@tcp(%s)/%s?tls=true",
    42  		dbUser, authToken, dbEndpoint, dbName,
    43  	)
    44  
    45  	const driverName = "stubSql"
    46  	sql.Register(driverName, &stubDriver{})
    47  	// Use db to perform SQL operations on database
    48  	if _, err = sql.Open(driverName, dnsStr); err != nil {
    49  		panic(err)
    50  	}
    51  
    52  	fmt.Println("Successfully opened connection to database")
    53  }