diff --git a/internal/db/main.go b/internal/db/main.go new file mode 100644 index 0000000..4611c36 --- /dev/null +++ b/internal/db/main.go @@ -0,0 +1,26 @@ +package db + +import ( + "context" + "git.libraryofcode.org/engineering/bces/config" + "github.com/redis/go-redis/v9" + "log" +) + +// NewRedisConnection takes a Config parameter and connects to the RedisURL provided in the config. It returns an instance of Redis Client. +// This function will exit the program if it cannot parse the URL properly nor connect successfully, and therefore doesn't return an error. +func NewRedisConnection(config config.Config) *redis.Client { + redisConnectionOptions, err := redis.ParseURL(config.RedisURL) + if err != nil { + log.Fatalf("Redis Connection URL is not valid or cannot parse given Connection URL: %s.\n\n%s", config.RedisURL, err) + } + redisClient := redis.NewClient(redisConnectionOptions) + + redisPingResponse, err := redisClient.Ping(context.Background()).Result() + if err != nil { + log.Fatalf("Could not ping Redis.\n\n%s", err) + } + log.Printf("Connected to Redis DB at <%s>: %s", config.RedisURL, redisPingResponse) + + return redisClient +}