Skip to content

Commit

Permalink
add HEAD process (#21)
Browse files Browse the repository at this point in the history
  • Loading branch information
sillygod authored Jun 24, 2020
1 parent 5800ff1 commit e6582ce
Show file tree
Hide file tree
Showing 3 changed files with 13 additions and 5 deletions.
2 changes: 1 addition & 1 deletion cmd/Caddyfile
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,7 @@

cache_type in_memory
match_path /
match_header Content-Type image/jpg image/png "text/plain; charset=utf-8"
match_header Content-Type image/jpg image/png "text/plain; charset=utf-8" "application/json" ""

}

Expand Down
14 changes: 11 additions & 3 deletions handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,6 @@ import (
"context"
"encoding/json"
"fmt"
"runtime/debug"
"time"

"net/http"
Expand Down Expand Up @@ -66,6 +65,13 @@ func (h *Handler) addStatusHeaderIfConfigured(w http.ResponseWriter, status stri
func (h *Handler) respond(w http.ResponseWriter, entry *Entry, cacheStatus string) error {
h.addStatusHeaderIfConfigured(w, cacheStatus)
copyHeaders(entry.Response.snapHeader, w.Header())

// when the request method is head, we don't need ot perform write body
if entry.Request.Method == "HEAD" {
w.WriteHeader(entry.Response.Code)
return nil
}

err := entry.WriteBodyTo(w)
return err
}
Expand Down Expand Up @@ -264,6 +270,10 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
if exists && previousEntry.isPublic {
if err := h.respond(w, previousEntry, cacheHit); err == nil {
return nil
} else if _, ok := err.(backends.NoPreCollectError); ok {
// if the err is No pre collect, just return nil
w.WriteHeader(previousEntry.Response.Code)
return nil
}
}

Expand Down Expand Up @@ -325,7 +335,6 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
err = h.respond(w, entry, cacheMiss)
if err != nil {
h.logger.Error("cache handler", zap.Error(err))
debug.PrintStack()
return caddyhttp.Error(entry.Response.Code, err)
}

Expand All @@ -335,7 +344,6 @@ func (h *Handler) ServeHTTP(w http.ResponseWriter, r *http.Request, next caddyht
err = h.respond(w, entry, cacheSkip)
if err != nil {
h.logger.Error("cache handler", zap.Error(err))
debug.PrintStack()
return caddyhttp.Error(entry.Response.Code, err)
}

Expand Down
2 changes: 1 addition & 1 deletion response.go
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@ import (
func copyHeaders(from http.Header, to http.Header) {
for k, values := range from {
for _, v := range values {
to.Add(k, v)
to.Set(k, v)
}
}
}
Expand Down

0 comments on commit e6582ce

Please sign in to comment.