break into own func and fix

This commit is contained in:
6543 2022-09-18 22:13:50 +02:00
parent 40478215d0
commit 4a2a14272b
No known key found for this signature in database
GPG key ID: B8BE6D610E61C862

View file

@ -153,12 +153,7 @@ func (client *Client) ServeRawContent(targetOwner, targetRepo, ref, resource str
mimeType := client.getMimeTypeByExtension(resource)
resp.Response.Header.Set(contentTypeHeader, mimeType)
contentLeng, err2 := strconv.ParseInt(resp.Header.Get(contentLengthHeader), 20, 64)
if err2 != nil {
log.Error().Err(err2).Msg("could not parse content length")
}
if contentLeng <= 0 && contentLeng > fileCacheSizeLimit {
// if content to big or could not be determined we return now
if !shouldRespBeSavedToCache(resp.Response) {
return reader, resp.Response, err
}
@ -170,16 +165,17 @@ func (client *Client) ServeRawContent(targetOwner, targetRepo, ref, resource str
// TODO: cache is half-empty if request is cancelled - does the ctx.Err() below do the trick?
// err = res.BodyWriteTo(io.MultiWriter(ctx.Response().BodyWriter(), &cacheBodyWriter))
*/
body, err := io.ReadAll(io.LimitReader(reader, contentLeng))
body, err := io.ReadAll(io.LimitReader(reader, fileCacheSizeLimit))
if err != nil {
if err := client.responseCache.Set(cacheKey, FileResponse{
Exists: true,
ETag: resp.Header.Get(eTagHeader),
MimeType: mimeType,
Body: body,
}, fileCacheTimeout); err != nil {
log.Error().Err(err).Msg("could not save content in cache")
}
log.Error().Err(err).Msg("not expected")
}
if err := client.responseCache.Set(cacheKey, FileResponse{
Exists: true,
ETag: resp.Header.Get(eTagHeader),
MimeType: mimeType,
Body: body,
}, fileCacheTimeout); err != nil {
log.Error().Err(err).Msg("could not save content in cache")
}
return io.NopCloser(bytes.NewReader(body)), resp.Response, nil
}
@ -259,3 +255,22 @@ func (client *Client) getMimeTypeByExtension(resource string) string {
}
return mimeType
}
func shouldRespBeSavedToCache(resp *http.Response) bool {
if resp == nil {
return false
}
contentLengRaw := resp.Header.Get(contentLengthHeader)
if contentLengRaw == "" {
return false
}
contentLeng, err := strconv.ParseInt(contentLengRaw, 10, 64)
if err != nil {
log.Error().Err(err).Msg("could not parse content length")
}
// if content to big or could not be determined we not cache it
return contentLeng > 0 && contentLeng < fileCacheSizeLimit
}