Skip to content

Commit

Permalink
Add HTTP Caching headers to links and thumbnails (#417)
Browse files Browse the repository at this point in the history
* Add HTTP Caching headers to links and thumbnails

* remove extra newline

* update changelog

* Need to create the PR first to get a number

* Add todo-note that we'll surely not forget

Co-authored-by: Rasmus Karlsson <rasmus.karlsson@pajlada.com>
  • Loading branch information
nuuls and pajlada committed Jan 23, 2023
1 parent aed6eee commit 031b678
Show file tree
Hide file tree
Showing 3 changed files with 22 additions and 2 deletions.
1 change: 1 addition & 0 deletions CHANGELOG.md
Original file line number Diff line number Diff line change
Expand Up @@ -31,6 +31,7 @@
- Dev: Resolve imgur.io links. (#365)
- Dev: Don't use `stampede` for link resolver links. (#394)
- Dev: Update to Twitter's v2 API. (#414)
- Dev: Add HTTP Caching headers. (#417)

## 1.2.3

Expand Down
6 changes: 4 additions & 2 deletions internal/resolvers/default/initialize.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,6 +6,7 @@ import (
"time"

"github.com/Chatterino/api/internal/db"
"github.com/Chatterino/api/pkg/cache"
"github.com/Chatterino/api/pkg/config"
"github.com/go-chi/chi/v5"
"github.com/go-chi/stampede"
Expand Down Expand Up @@ -34,7 +35,8 @@ func Initialize(ctx context.Context, cfg config.APIConfig, pool db.Pool, router
imageCached := stampede.Handler(256, 2*time.Second)
generatedValuesCached := stampede.Handler(256, 2*time.Second)

router.Get("/link_resolver/{url}", defaultLinkResolver.HandleRequest)
router.With(imageCached).Get("/thumbnail/{url}", defaultLinkResolver.HandleThumbnailRequest)
// TODO: Make the max age headers be applied based on the resolved link's configured cache timer
router.With(cache.MaxAgeHeaders(time.Minute*10)).Get("/link_resolver/{url}", defaultLinkResolver.HandleRequest)
router.With(cache.MaxAgeHeaders(time.Minute*10), imageCached).Get("/thumbnail/{url}", defaultLinkResolver.HandleThumbnailRequest)
router.With(generatedValuesCached).Get("/generated/{url}", defaultLinkResolver.HandleGeneratedValueRequest)
}
17 changes: 17 additions & 0 deletions pkg/cache/middleware.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,17 @@
package cache

import (
"fmt"
"net/http"
"time"
)

// MaxAgeHeaders adds the Cache-Control: max-age=$TTL header to every response
func MaxAgeHeaders(ttl time.Duration) func(next http.Handler) http.Handler {
return func(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Cache-Control", fmt.Sprintf("max-age=%.0f", ttl.Seconds()))
next.ServeHTTP(w, r)
})
}
}

0 comments on commit 031b678

Please sign in to comment.