英文:
How to stop ReverseProxy from proxying request
问题
有没有办法阻止httputil.ReverseProxy
将传入的请求发送到目标服务器?例如,如果我有一个缓存,并且可以仅使用本地数据响应客户端。或者在验证之后,我想向客户端返回一个错误。
英文:
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.
答案1
得分: 2
你应该能够使用缓存包装http.DefaultTransport
,该缓存可以根据请求使用缓存,或者回退到http.DefaultTransport
。
package main
import (
"net/http"
"net/http/httputil"
)
var _ http.RoundTripper = &CachingTransport{}
type CachingTransport struct {
// 在这里放置你的缓存
}
func (c *CachingTransport) RoundTrip(request *http.Request) (*http.Response, error) {
// 确定是否使用缓存并返回,或者使用默认传输
return http.DefaultTransport.RoundTrip(request)
}
func main() {
_ = httputil.ReverseProxy{
Transport: &CachingTransport{},
}
}
英文:
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{},
}
}
答案2
得分: 2
httputil.ReverseProxy
是一个具有单个导出方法的类型,ServeHTTP(rw http.ResponseWriter, req *http.Request)
,使其实现了net/http.Handler
接口。
因此,基本上在你现在使用httputil.ReverseProxy
实例的地方,可以使用一个实现了net/http.Handler
接口的自定义类型的实例。该自定义类型保持对httputil.ReverseProxy
实例的指针,并且可以自行处理请求或调用该ReverseProxy
实例的ServeHTTP
方法。
英文:
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
.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论