Created
July 31, 2017 19:56
-
-
Save jacoelho/56ad6e74d4d1168ca3f36977584b3332 to your computer and use it in GitHub Desktop.
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
type Cache struct { | |
kv map[string]*bufio.Reader | |
http.RoundTripper | |
} | |
func (c *Cache) RoundTrip(req *http.Request) (*http.Response, error) { | |
if req.Method != "GET" { | |
return c.RoundTrip(req) | |
} | |
v, ok := c.kv[req.URL.String()] | |
if ok { | |
// return cached | |
return http.ReadResponse(v, nil) | |
} | |
resp, err := c.RoundTripper.RoundTrip(req) | |
if err != nil { | |
return resp, err | |
} | |
body, err := httputil.DumpResponse(resp, true) | |
if err != nil { | |
return resp, err | |
} | |
r := bufio.NewReader(bytes.NewReader(body)) | |
c.kv[req.URL.String()] = r | |
return resp, err | |
} | |
func main() { | |
c := &http.Client{ | |
Transport: &Cache{ | |
RoundTripper: http.DefaultTransport, | |
kv: make(map[string]*bufio.Reader), | |
}, | |
} | |
req, err := http.NewRequest("GET", "https://www.google.com", nil) | |
if err != nil { | |
log.Fatalf("Could not create request") | |
} | |
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second) | |
defer cancel() | |
req = req.WithContext(ctx) | |
resp, err := c.Do(req) | |
if err != nil { | |
log.Fatalln(err) | |
} | |
resp.Body.Close() | |
log.Println(resp) | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment