working version

This commit is contained in:
shortcut 2021-06-28 16:14:59 -04:00
parent f064ddb668
commit c4988518f3
2 changed files with 11 additions and 6 deletions

1
.gitignore vendored
View File

@ -34,3 +34,4 @@ go.mod
go.sum
index.html
dist
caddy/caddy

View File

@ -57,9 +57,11 @@ func (s Webp) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.H
return next.ServeHTTP(w, r)
}
repl := r.Context().Value(caddy.ReplacerCtxKey).(*caddy.Replacer)
rootPath,_:=repl.GetString("{http.vars.root}")
cacheFile:=fmt.Sprintf("%s%s",caddyhttp.SanitizedPathJoin(rootPath + "/.webpcache/", r.URL.Path +"?" + r.URL.RawQuery))
origFile:=caddyhttp.SanitizedPathJoin(rootPath, r.URL.Path)
root := repl.ReplaceAll("{http.vars.root}", ".")
cacheFile:=fmt.Sprintf("%s%s",caddyhttp.SanitizedPathJoin(root + "/.webpcache/", r.URL.Path +"?"), r.URL.RawQuery)
origFile := caddyhttp.SanitizedPathJoin(root, r.URL.Path)
cstat, err:=os.Stat(cacheFile)
if err==nil {
// Cache file exists
@ -70,7 +72,7 @@ func (s Webp) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.H
if err == nil {
// We couldn't open for whatever reason so let's not serve it
w.Header().Set("content-type", "image/webp")
w.Header().Set("webpstatus", "fromcache")
w.Header().Add("webpstatus", "fromcache")
w.WriteHeader(http.StatusOK)
io.Copy(w,fh)
return nil
@ -82,7 +84,7 @@ func (s Webp) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.H
cachePath,_:=path.Split(cacheFile)
_,err=os.Stat(cachePath)
if err != nil {
err=os.Mkdir(cachePath, 0600)
err=os.MkdirAll(cachePath, 0600)
if err != nil {
log.Printf("Creating cache path: " + err.Error())
}
@ -128,7 +130,9 @@ func (s Webp) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyhttp.H
buf.WriteTo(fh)
fh.Close()
w.Header().Set("Content-Type", "image/webp")
w.Header().Set("content-Type", "image/webp")
w.Header().Add("webpstatus", "tocache")
w.WriteHeader(http.StatusOK)
buf.WriteTo(w)
return nil