func handler(p *httputil.ReverseProxy, redisClient *redis.Client) func(http.ResponseWriter, *http.Request) { return func(w http.ResponseWriter, r *http.Request) { hash := hashKey(r) serializableResponse := SerializableResponse{make(map[string][]string), nil} s, err := redisClient.Get(hash) if err != nil { // The request is not cached rec := httptest.NewRecorder() log.Println("Non cached: " + hash) // Perform the real request and cache it p.ServeHTTP(rec, r) for k, v := range rec.Header() { serializableResponse.Header[k] = v } serializableResponse.Body = rec.Body.Bytes() jsonResponse, err := json.Marshal(serializableResponse) if err != nil { panic(err) } redisClient.Set(hash, jsonResponse) w.Header().Set("X-Eidetic", "Live request") } else { // The request is cached log.Println("Cached!: " + hash) // Load the cached request err = json.Unmarshal([]byte(s), &serializableResponse) if err != nil { panic(err) } w.Header().Set("X-Eidetic", "Cached request") } //Copy the data to the actual ResponseWriter // log.Println("\n\n\nResponse Headers:") for k, v := range serializableResponse.Header { w.Header()[k] = v // log.Println(k + ": ") // for _, str := range v { // log.Println(" " + str) // } } w.Write([]byte(serializableResponse.Body)) // log.Println("\nResponse body:\n" + string(serializableResponse.Body)) } }
func main() { var client *redis.Client client = redis.New() client.Connect("localhost", 6379) s, _ := client.Ping() fmt.Println(s) client.Incr("hello") s, _ = client.Get("hello") fmt.Println(s) client.Quit() }