From 14d2165dafedbef8989db9713fcc98d8bfa58c0f Mon Sep 17 00:00:00 2001 From: Alex Csengery Date: Tue, 29 Aug 2023 21:55:30 -0400 Subject: [PATCH] rewrite getCredentials to be more generic --- main.go | 39 ++++++++++++++++++++++++--------------- s3helper/s3helper.go | 4 ++-- 2 files changed, 26 insertions(+), 17 deletions(-) diff --git a/main.go b/main.go index a40ba3f..10e0da9 100644 --- a/main.go +++ b/main.go @@ -3,6 +3,7 @@ package main import ( "backup-tool/s3helper" "context" + "fmt" "log" "os" @@ -11,24 +12,32 @@ import ( func main() { - accessKeyID, secretAccessKey := getCredentials() - s3helper.UploadFile(context.Background(), accessKeyID, secretAccessKey) - -} - -func getCredentials() (string, string) { - // get credentials from env vars err := godotenv.Load() if err != nil { log.Fatalf("error loading .env file: (%s)", err.Error()) } - keyName := os.Getenv("KEY_ID") - if keyName == "" { - log.Fatal("missing or empty KEY_ID") + + if len(os.Args) > 1 { + // only do this if we have been given a file to upload (for now) + // TODO: have this tool take the backup of the DB itself + b2Creds, err := getCredentials([]string{"B2_KEY_ID", "B2_APPLICATION_KEY"}) + if err != nil { + log.Fatalf("could not get B2 credentials: %s", err) + } + s3helper.UploadFile(context.Background(), b2Creds) } - applicationKey := os.Getenv("APPLICATION_KEY") - if applicationKey == "" { - log.Fatal("missing or empty APPLICATION_KEY") - } - return keyName, applicationKey + +} + +func getCredentials(credNames []string) (map[string]string, error) { + creds := map[string]string{} + for _, name := range credNames { + value := os.Getenv(name) + if value == "" { + return nil, fmt.Errorf("missing or empty ENV var: %s", name) + } + creds[name] = value + } + + return creds, nil } diff --git a/s3helper/s3helper.go b/s3helper/s3helper.go index 25e2770..d92d6e5 100644 --- a/s3helper/s3helper.go +++ b/s3helper/s3helper.go @@ -14,9 +14,9 @@ const ( BUCKETNAME = "ducimon-db-backups" ) -func UploadFile(ctx context.Context, accessKeyID, secretAccessKey) error { +func UploadFile(ctx context.Context, b2Creds map[string]string) error { - client := createClient(accessKeyID, secretAccessKey) + client := createClient(b2Creds["B2_KEY_ID"], b2Creds["B2_APPLICATION_KEY"]) verifyBucket(client, ctx) absolutePath, basename := validateUploadFile() _, err := client.FPutObject(ctx, BUCKETNAME, "test", absolutePath, minio.PutObjectOptions{})