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.
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)
}
How do I avoid rehashing overhead with std::set in multithreaded code?
How do I find elements with custom comparators with std::set for embedded targets?
How do I erase elements while iterating with std::set for embedded targets?
How do I provide stable iteration order with std::unordered_map for large datasets?
How do I reserve capacity ahead of time with std::unordered_map for large datasets?
How do I erase elements while iterating with std::unordered_map in multithreaded code?
How do I provide stable iteration order with std::map for embedded targets?
How do I provide stable iteration order with std::map in multithreaded code?
How do I avoid rehashing overhead with std::map in performance-sensitive code?
How do I merge two containers efficiently with std::map for embedded targets?