tetafro
tetafro

Reputation: 546

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.

Upvotes: 1

Views: 814

Answers (2)

Clark McCauley
Clark McCauley

Reputation: 1457

You should be able to wrap the http.DefaultTransport with a cache that can either use the cache based on the request or fallback on the http.DefaultTransport.

package main

import (
    "net/http"
    "net/http/httputil"
)

var _ http.RoundTripper = &CachingTransport{}

type CachingTransport struct {
    // put your cache here  
}

func (c *CachingTransport) RoundTrip(request *http.Request) (*http.Response, error) {
    // determine whether to use the cache and return, or use the default transport
    return http.DefaultTransport.RoundTrip(request)
}

func main() {
    _ = httputil.ReverseProxy{
        Transport: &CachingTransport{},
    }
}

Upvotes: 2

kostix
kostix

Reputation: 55493

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.

Upvotes: 3

Related Questions