// 2020 Rackspace, Inc. // // Licensed under the Apache License, Version 2.0 (the "License"): you may // not use this file except in compliance with the License. You may obtain // a copy of the License at // // http://www.apache.org/licenses/LICENSE-2.0 // // Unless required by applicable law or agreed to in writing, software // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the // License for the specific language governing permissions and limitations // under the License. package tools import ( "context" "fmt" redisPkg "github.com/go-redis/redis/v7" ) type contextKey int const redisKey contextKey = 0 // NewCtxRedis function will take an initialized *redis.Client, and store // the value in the http context for later retrieval. func NewCtxRedis(ctx context.Context, client *redisPkg.Client) context.Context { return context.WithValue(ctx, redisKey, client) } // FromCtxRedis function will pull the *redis.Client from the http context. func FromCtxRedis(ctx context.Context) *redisPkg.Client { return ctx.Value(redisKey).(*redisPkg.Client) } // NewRedis function creates an instance of the redis.Client and // returns the client back to the caller. func NewRedis(redisKey string, staging bool) (*redisPkg.Client, error) { cache := redisPkg.NewClient(&redisPkg.Options{ Addr: "redis.nsi.rackspace.com:6379", Password: redisKey, DB: 0, // use default DB }) if !staging { if _, err := cache.Ping().Result(); err != nil { return cache, fmt.Errorf("error connecting to redis DB Ping(): %s", err) } } return cache, nil }