@@ -10,32 +10,19 @@ import (
1010 "path/filepath"
1111)
1212
13- func getCacheFilePath (endpoint string ) string {
14- hash := fnv .New64a ()
15- hash .Write ([]byte (endpoint ))
16- hashedEndpoint := fmt .Sprintf ("%x" , hash .Sum (nil ))
17- return filepath .Join (".ditto" , hashedEndpoint )
18- }
19-
20- func retrieve (endpoint string ) ([]byte , error ) {
21- cacheFilePath := getCacheFilePath (endpoint )
22- if _ , err := os .Stat (cacheFilePath ); os .IsNotExist (err ) {
23- return nil , err
13+ func Client () * http.Client {
14+ return & http.Client {
15+ Transport : & CachingTransport {
16+ Transport : http .DefaultTransport ,
17+ },
2418 }
25- return os .ReadFile (cacheFilePath )
26- }
27-
28- func cache (endpoint string , data []byte ) error {
29- cacheFilePath := getCacheFilePath (endpoint )
30- os .MkdirAll (filepath .Dir (cacheFilePath ), os .ModePerm )
31- return os .WriteFile (cacheFilePath , data , 0644 )
3219}
3320
34- type CachingHTTPClient struct {
21+ type CachingTransport struct {
3522 Transport http.RoundTripper
3623}
3724
38- func (c * CachingHTTPClient ) RoundTrip (req * http.Request ) (* http.Response , error ) {
25+ func (c * CachingTransport ) RoundTrip (req * http.Request ) (* http.Response , error ) {
3926 endpoint := req .URL .String ()
4027
4128 data , err := retrieve (endpoint )
@@ -65,3 +52,24 @@ func (c *CachingHTTPClient) RoundTrip(req *http.Request) (*http.Response, error)
6552 resp .Body = io .NopCloser (bytes .NewReader (data ))
6653 return resp , nil
6754}
55+
56+ func getCacheFilePath (endpoint string ) string {
57+ hash := fnv .New64a ()
58+ hash .Write ([]byte (endpoint ))
59+ hashedEndpoint := fmt .Sprintf ("%x" , hash .Sum (nil ))
60+ return filepath .Join (".ditto" , hashedEndpoint )
61+ }
62+
63+ func retrieve (endpoint string ) ([]byte , error ) {
64+ cacheFilePath := getCacheFilePath (endpoint )
65+ if _ , err := os .Stat (cacheFilePath ); os .IsNotExist (err ) {
66+ return nil , err
67+ }
68+ return os .ReadFile (cacheFilePath )
69+ }
70+
71+ func cache (endpoint string , data []byte ) error {
72+ cacheFilePath := getCacheFilePath (endpoint )
73+ os .MkdirAll (filepath .Dir (cacheFilePath ), os .ModePerm )
74+ return os .WriteFile (cacheFilePath , data , 0644 )
75+ }
0 commit comments