From e6582ce9a657e8077cdcc8b7bdace7b31d288a3a Mon Sep 17 00:00:00 2001 From: jing Date: Wed, 24 Jun 2020 22:54:30 +0800 Subject: [PATCH] add HEAD process (#21) --- cmd/Caddyfile | 2 +- handler.go | 14 +++++++++++--- response.go | 2 +- 3 files changed, 13 insertions(+), 5 deletions(-) diff --git a/cmd/Caddyfile b/cmd/Caddyfile index f890c00..5ae0b68 100644 --- a/cmd/Caddyfile +++ b/cmd/Caddyfile @@ -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" "" } diff --git a/handler.go b/handler.go index ad5b3e8..9233b68 100644 --- a/handler.go +++ b/handler.go @@ -4,7 +4,6 @@ import ( "context" "encoding/json" "fmt" - "runtime/debug" "time" "net/http" @@ -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 } @@ -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 } } @@ -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) } @@ -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) } diff --git a/response.go b/response.go index 04baa26..600238c 100644 --- a/response.go +++ b/response.go @@ -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) } } }