(ctx *context.Context)
| 127 | } |
| 128 | |
| 129 | func (h *Handler) ServeHTTP(ctx *context.Context) { |
| 130 | // check for pre-cache validators, if at least one of them return false |
| 131 | // for this specific request, then skip the whole cache |
| 132 | bodyHandler := ctx.NextHandler() |
| 133 | if bodyHandler == nil { |
| 134 | emptyHandler(ctx) |
| 135 | return |
| 136 | } |
| 137 | // skip prepares the context to move to the next handler if the "nextHandler" has a ctx.Next() inside it, |
| 138 | // even if it's not executed because it's cached. |
| 139 | ctx.Skip() |
| 140 | |
| 141 | if !h.rule.Claim(ctx) { |
| 142 | bodyHandler(ctx) |
| 143 | return |
| 144 | } |
| 145 | |
| 146 | key := getOrSetKey(ctx) // unique per subdomains and paths with different url query. |
| 147 | |
| 148 | e := h.entryStore.Get(key) |
| 149 | if e == nil { |
| 150 | // if it's expired, then execute the original handler |
| 151 | // with our custom response recorder response writer |
| 152 | // because the net/http doesn't give us |
| 153 | // a builtin way to get the status code & body |
| 154 | recorder := ctx.Recorder() |
| 155 | bodyHandler(ctx) |
| 156 | |
| 157 | // now that we have recordered the response, |
| 158 | // we are ready to check if that specific response is valid to be stored. |
| 159 | |
| 160 | // check if it's a valid response, if it's not then just return. |
| 161 | if !h.rule.Valid(ctx) { |
| 162 | return |
| 163 | } |
| 164 | |
| 165 | // no need to copy the body, its already done inside |
| 166 | body := recorder.Body() |
| 167 | if len(body) == 0 { |
| 168 | // if no body then just exit. |
| 169 | return |
| 170 | } |
| 171 | |
| 172 | // fmt.Printf("reset cache entry\n") |
| 173 | // fmt.Printf("key: %s\n", key) |
| 174 | // fmt.Printf("content type: %s\n", recorder.Header().Get(cfg.ContentTypeHeader)) |
| 175 | // fmt.Printf("body len: %d\n", len(body)) |
| 176 | |
| 177 | r := entry.NewResponse(recorder.StatusCode(), recorder.Header(), body) |
| 178 | e = h.entryPool.Acquire(h.maxAgeFunc(ctx), r, func() { |
| 179 | h.entryStore.Delete(key) |
| 180 | }) |
| 181 | |
| 182 | h.entryStore.Set(key, e) |
| 183 | return |
| 184 | } |
| 185 | |
| 186 | // if it's valid then just write the cached results |
nothing calls this directly
no test coverage detected