| 51 | ) |
| 52 | |
| 53 | func RespondWithData(rw http.ResponseWriter, data io.Reader, metadata cache.ContentMetadata, ttl time.Duration, cacheHit string, statusCode int, labels prometheus.Labels) error { |
| 54 | h := rw.Header() |
| 55 | if len(metadata.Type) > 0 { |
| 56 | h.Set("Content-Type", metadata.Type) |
| 57 | } |
| 58 | |
| 59 | if len(metadata.Encoding) > 0 { |
| 60 | h.Set("Content-Encoding", metadata.Encoding) |
| 61 | } |
| 62 | |
| 63 | h.Set("Content-Length", fmt.Sprintf("%d", metadata.Length)) |
| 64 | if ttl > 0 { |
| 65 | expireSeconds := uint(ttl / time.Second) |
| 66 | h.Set("Cache-Control", fmt.Sprintf("max-age=%d", expireSeconds)) |
| 67 | } |
| 68 | |
| 69 | h.Set("X-Cache", cacheHit) |
| 70 | |
| 71 | rw.WriteHeader(statusCode) |
| 72 | |
| 73 | if _, err := io.Copy(rw, data); err != nil { |
| 74 | var perr *cache.RedisCacheError |
| 75 | |
| 76 | if errors.As(err, &perr) { |
| 77 | cacheCorruptedFetch.With(labels).Inc() |
| 78 | log.Debugf("redis cache error") |
| 79 | } |
| 80 | log.Errorf("cannot send response to client: %s", err) |
| 81 | return fmt.Errorf("cannot send response to client: %w", err) |
| 82 | } |
| 83 | |
| 84 | return nil |
| 85 | } |
| 86 | |
| 87 | func (rw *statResponseWriter) SetStatusCode(code int) { |
| 88 | rw.statusCode = code |