如何停止 ReverseProxy 代理请求的转发。

huangapple go评论96阅读模式
英文:

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.

huangapple
  • 本文由 发表于 2021年7月7日 23:01:08
  • 转载请务必保留本文链接:https://go.coder-hub.com/68288483.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定