Search code examples
httpgoreverse-proxy

How to stop ReverseProxy from proxying request


Is there any way to prevent httputil.ReverseProxy from sending an incoming request to the target server? For example, if I have a cache and I can respond to the client using only local data. Or after validation, I want to return an error to the client.


Solution

  • A httputil.ReverseProxy has a single exported method, ServeHTTP(rw http.ResponseWriter, req *http.Request) which makes it implement the net/http.Handler interface.

    So basically at a place you're now using an vanilla httputil.ReverseProxy instance, instead use an instance of your custom type which implements net/http.Handler as well, keeps a pointer to an instance of httputil.ReverseProxy, and either processes the request itself or calls out to that ReverseProxy instance's ServeHTTP.