github.com/mgoltzsche/ctnr@v0.7.1-alpha/pkg/fs/source/httpheadercache.go (about) 1 package source 2 3 import ( 4 "encoding/base64" 5 "encoding/json" 6 "io/ioutil" 7 "os" 8 "path/filepath" 9 10 "github.com/mgoltzsche/ctnr/pkg/atomic" 11 "github.com/pkg/errors" 12 ) 13 14 type HttpHeaderCache interface { 15 // Restores cached attrs or null 16 GetHttpHeaders(url string) (*HttpHeaders, error) 17 // Stores URL attrs 18 PutHttpHeaders(url string, attrs *HttpHeaders) error 19 } 20 21 type HttpHeaders struct { 22 ContentLength int64 23 Etag string 24 LastModified string 25 } 26 27 type httpHeaderCache string 28 29 func NewHttpHeaderCache(dir string) HttpHeaderCache { 30 return httpHeaderCache(dir) 31 } 32 33 func (c httpHeaderCache) GetHttpHeaders(url string) (*HttpHeaders, error) { 34 b, err := ioutil.ReadFile(c.file(url)) 35 if err != nil { 36 if os.IsNotExist(err) { 37 return nil, nil 38 } 39 return nil, errors.Wrap(err, "HTTPHeaderCache") 40 } 41 h := HttpHeaders{} 42 return &h, errors.Wrap(json.Unmarshal(b, &h), "HTTPHeaderCache") 43 } 44 45 func (c httpHeaderCache) PutHttpHeaders(url string, attrs *HttpHeaders) error { 46 file := c.file(url) 47 os.MkdirAll(filepath.Dir(file), 0775) 48 _, err := atomic.WriteJson(file, attrs) 49 return errors.Wrap(err, "HTTPHeaderCache") 50 } 51 52 func (c httpHeaderCache) file(url string) string { 53 return filepath.Join(string(c), base64.RawStdEncoding.EncodeToString([]byte(url))) 54 } 55 56 type NoopHttpHeaderCache string 57 58 func (c NoopHttpHeaderCache) GetHttpHeaders(url string) (*HttpHeaders, error) { 59 return nil, nil 60 } 61 62 func (c NoopHttpHeaderCache) PutHttpHeaders(url string, attrs *HttpHeaders) error { 63 return nil 64 }