ServeHTTP , or remote cache client whatever you like, it's the client-side function of the ServeHTTP sends a request to the server-side remote cache Service and sends the cached response to the frontend client it is used only when you achieved something like horizontal scaling (separate machines) lo
(ctx *context.Context)
| 95 | // |
| 96 | // client-side function |
| 97 | func (h *ClientHandler) ServeHTTP(ctx *context.Context) { |
| 98 | // check for deniers, if at least one of them return true |
| 99 | // for this specific request, then skip the whole cache |
| 100 | if !h.rule.Claim(ctx) { |
| 101 | h.bodyHandler(ctx) |
| 102 | return |
| 103 | } |
| 104 | |
| 105 | uri := &uri.URIBuilder{} |
| 106 | uri.ServerAddr(h.remoteHandlerURL).ClientURI(ctx.Request().URL.RequestURI()).ClientMethod(ctx.Request().Method) |
| 107 | |
| 108 | // set the full url here because below we have other issues, probably net/http bugs |
| 109 | request, err := http.NewRequest(http.MethodGet, uri.String(), nil) |
| 110 | if err != nil { |
| 111 | //// println("error when requesting to the remote service: " + err.Error()) |
| 112 | // somehing very bad happens, just execute the user's handler and return |
| 113 | h.bodyHandler(ctx) |
| 114 | return |
| 115 | } |
| 116 | |
| 117 | // println("GET Do to the remote cache service with the url: " + request.URL.String()) |
| 118 | response, err := Client.Do(request) |
| 119 | |
| 120 | if err != nil || response.StatusCode == cfg.FailStatus { |
| 121 | |
| 122 | // if not found on cache, then execute the handler and save the cache to the remote server |
| 123 | recorder := ctx.Recorder() |
| 124 | h.bodyHandler(ctx) |
| 125 | |
| 126 | // check if it's a valid response, if it's not then just return. |
| 127 | if !h.rule.Valid(ctx) { |
| 128 | return |
| 129 | } |
| 130 | // save to the remote cache |
| 131 | // we re-create the request for any case |
| 132 | body := recorder.Body()[0:] |
| 133 | if len(body) == 0 { |
| 134 | //// println("Request: len body is zero, do nothing") |
| 135 | return |
| 136 | } |
| 137 | uri.StatusCode(recorder.StatusCode()) |
| 138 | uri.Lifetime(h.life) |
| 139 | uri.ContentType(recorder.Header().Get(cfg.ContentTypeHeader)) |
| 140 | |
| 141 | request, err = http.NewRequest(http.MethodPost, uri.String(), bytes.NewBuffer(body)) // yes new buffer every time |
| 142 | |
| 143 | // println("POST Do to the remote cache service with the url: " + request.URL.String()) |
| 144 | if err != nil { |
| 145 | //// println("Request: error on method Post of request to the remote: " + err.Error()) |
| 146 | return |
| 147 | } |
| 148 | // go Client.Do(request) |
| 149 | resp, err := Client.Do(request) |
| 150 | if err != nil { |
| 151 | return |
| 152 | } |
| 153 | resp.Body.Close() |
| 154 | } else { |
nothing calls this directly
no test coverage detected