Skip to content

Commit

Permalink
fix: add cdn support
Browse files Browse the repository at this point in the history
  • Loading branch information
theredrad committed Sep 27, 2021
1 parent a8cafdf commit 44ae70c
Showing 1 changed file with 22 additions and 2 deletions.
24 changes: 22 additions & 2 deletions api/api.go
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,8 @@ type Options struct {
MaxWidth int
MinHeight int
MaxHeight int

CDN string
}

const (
Expand Down Expand Up @@ -108,6 +110,12 @@ func (a *API) SizeHandler(w http.ResponseWriter, r *http.Request) {
cp := cachePath(file, width, height)
if _, err := os.Stat(cp); err == nil {
log.Printf("cached file found: %s", file)

if a.opt.CDN != "" { // redirect to cdn
http.Redirect(w, r, fmt.Sprintf("%s/%s", a.opt.CDN, cp), 302)
return
}

err = handleCacheFile(w, cp)
if err == nil {
return
Expand Down Expand Up @@ -136,7 +144,19 @@ func (a *API) SizeHandler(w http.ResponseWriter, r *http.Request) {
}

if a.opt.CacheFiles {
go func() {
if a.opt.CDN != "" { // store file & redirect to cdn
cp := cachePath(file, width, height)
err := cacheFile(cp, buffer.Bytes())
if err != nil {
log.Printf("error while caching file: %s : %v", cp, err)
return
}

http.Redirect(w, r, fmt.Sprintf("%s/%s", a.opt.CDN, cp), 302)
return
}

go func() { // store file in a goroutine
cp := cachePath(file, width, height)
err := cacheFile(cp, buffer.Bytes())
if err != nil {
Expand Down Expand Up @@ -222,4 +242,4 @@ func cachePath(file string, width, height int) string {
func path(file string) string {
tmp := strings.Split(file, "/")
return strings.Join(tmp[:len(tmp)-1], "/")
}
}

0 comments on commit 44ae70c

Please sign in to comment.