How do I cache HTTP responses with Redis in Go?

Caching HTTP responses is an effective way to optimize the performance of your Go applications by reducing the load on external services and speeding up response times. In this example, we'll demonstrate how to use Redis as a caching layer for HTTP responses in Go.

Example Code

package main import ( "encoding/json" "net/http" "github.com/go-redis/redis/v8" "context" "time" ) var ctx = context.Background() func main() { rdb := redis.NewClient(&redis.Options{ Addr: "localhost:6379", }) http.HandleFunc("/data", func(w http.ResponseWriter, r *http.Request) { // Check if response is in cache cachedData, err := rdb.Get(ctx, "cached_data").Result() if err == nil { // Return cached response w.Header().Set("Content-Type", "application/json") w.Write([]byte(cachedData)) return } // Simulate fetching new data responseData := map[string]string{"message": "Hello, world!"} jsonData, _ := json.Marshal(responseData) // Store response in Redis cache rdb.Set(ctx, "cached_data", jsonData, 10*time.Minute) // Return new response w.Header().Set("Content-Type", "application/json") w.Write(jsonData) }) http.ListenAndServe(":8080", nil) }

Go Redis HTTP Caching Performance Optimization Go Redis Example