I'm trying to create a reverse proxy that takes all requests and redirect them into a target url, like google.com or any other API. Unfortunately, all targets returns errors like page Not Found, or Forbidden Errors
func main() {
r := gin.Default()
eanAPI := api.NewEanAPI()
routers.InitRedirectRoutes(r, eanAPI)
port := os.Getenv("PORT")
if len(port) == 0 {
port = "8000"
}
r.Run(":" + port)
}
// InitRedirectRoutes initialize routes redirection.
func InitRedirectRoutes(r *gin.Engine, eanAPI api.EanAPI) {
r.POST("/*action", eanAPI.ReverseProxy)
r.GET("/*action", eanAPI.ReverseProxy)
}
type EanAPI interface {
ReverseProxy(ctx *gin.Context)
}
type eanAPI struct {
baseURL string
}
func NewEanAPI() EanAPI {
return &eanAPI{}
}
func (api *eanAPI) ReverseProxy(ctx *gin.Context) {
// proxy
forwardToHost := "http://httpbin.org/"
// I tried with "https://jsonplaceholder.typicode.com/"
"http://google.com"
reverseProxy := proxy.NewProxy(forwardToHost)
reverseProxy.Handle(ctx.Writer, ctx.Request, url.Parse(forwardToHost))
}
type Prox struct {
target *url.URL
proxy *httputil.ReverseProxy
}
func NewProxy(target string) *Prox {
url, _ := url.Parse(target)
fmt.Println("url", url)
return &Prox{target: url, proxy: httputil.NewSingleHostReverseProxy(url)}
}
func (p *Prox) Handle(w http.ResponseWriter, r *http.Request, origin *url.URL) {
w.Header().Set("Content-Type", "application/json; charset=utf-8")
w.Header().Set("X-Forwarded-Host", r.Host)
w.Header().Set("X-Origin-Host", origin.Host)
r.URL.Scheme = origin.Scheme
r.URL.Host = origin.Host
p.proxy.ServeHTTP(w, r)
}
I spent many days trying to set appropriate headers but nothing worked so far. I think the headers were not set correctly but I don't how to copy headers from client and add it to the proxy.
I'm using a proxy instead of a redirect because I have to do some work with the body request and response!
Thanks in advance!