Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Golang reverse proxy returns Not found or Forbidden Errors

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!

like image 868
Nizar AYARI Avatar asked Feb 14 '26 00:02

Nizar AYARI


1 Answers

Not sure if this will help but https://golang.org/pkg/net/http/httputil/#ReverseProxy you can use the Director function to debug and change the path of the request, inspect the incoming reques. Also make sure to change not only the req.URL.Host but change the req.Host too cause that one is going to be picked up by apache/nginx virtual hosts settings. Dont give up and remember to have fun :)

like image 188
sirfilip Avatar answered Feb 16 '26 17:02

sirfilip



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!