1
0
Fork 0
mirror of https://github.com/Luzifer/preserve.git synced 2024-11-12 16:12:45 +00:00
preserve/cache.go

66 lines
1.4 KiB
Go
Raw Permalink Normal View History

2020-06-14 00:09:06 +00:00
package main
import (
"context"
"crypto/sha256"
"fmt"
2020-06-14 00:09:06 +00:00
"net/http"
"path"
"time"
"github.com/Luzifer/preserve/pkg/storage"
2020-06-14 00:09:06 +00:00
"github.com/pkg/errors"
"github.com/sirupsen/logrus"
2020-06-14 00:09:06 +00:00
)
const lastSuccessStatus = 299
func renewCache(ctx context.Context, url string) (*storage.Meta, error) {
cachePath := urlToCachePath(url)
2020-06-14 00:09:06 +00:00
req, err := http.NewRequestWithContext(ctx, http.MethodGet, url, nil)
if err != nil {
return nil, errors.Wrap(err, "Unable to create request")
}
if cfg.UserAgent != "" {
req.Header.Set("User-Agent", cfg.UserAgent)
}
resp, err := http.DefaultClient.Do(req)
2020-06-14 00:09:06 +00:00
if err != nil {
return nil, errors.Wrap(err, "Unable to fetch source file")
}
defer func() {
if err := resp.Body.Close(); err != nil {
logrus.WithError(err).Error("closing response body (leaked fd)")
}
}()
2020-06-14 00:09:06 +00:00
if resp.StatusCode > lastSuccessStatus {
2020-06-14 00:09:06 +00:00
return nil, errors.Errorf("HTTP status signaled failure: %d", resp.StatusCode)
}
lm := time.Now()
2020-06-14 00:09:06 +00:00
if t, err := time.Parse(http.TimeFormat, resp.Header.Get("Last-Modified")); err == nil {
lm = t
}
metadata := &storage.Meta{
2020-06-14 00:09:06 +00:00
ContentType: resp.Header.Get("Content-Type"),
LastCached: time.Now(),
LastModified: lm,
}
if err := store.StoreFile(ctx, cachePath, metadata, resp.Body); err != nil {
return nil, fmt.Errorf("storing file: %w", err)
}
return metadata, nil
}
func urlToCachePath(url string) string {
h := fmt.Sprintf("%x", sha256.Sum256([]byte(url)))
return path.Join(h[0:2], h)
2020-06-14 00:09:06 +00:00
}