Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Add HTTP Caching headers to links and thumbnails #417

Merged
merged 5 commits into from
Jan 23, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
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)
})
}
}