Chryses
Chryses

Reputation: 181

GoLang Reverse Proxy Multiple Target URLs Without Appending Subpaths

I am trying to write a reverse proxy in Golang using net/httputil/ReverseProxy that is able to forward requests to different target URLs without appending the proxy URL subpaths.

For example: If my proxy URL is PROXYURL, (not enough reputation to post more than 8 links, even fake example ones, so hence replacing link with PROXYURL),

I would like PROXYURL/app1 to forward requests to TARGET1/directory and I would like PROXYURL/app2 to forward to TARGET2/directory2

Currently, I create the following ReverseProxy http handlers using NewSingleHostReverseProxy() and bind them to the desired subpaths (/app1 and /app2).

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

func main() {
    port := "6666"
    proxy1 = httputil.NewSingleHostReverseProxy("http://target1.com/directory")
    proxy2 = httputil.NewSingleHostReverseProxy("http://target2.com/directory2")

    http.Handle("/app1", proxy1)
    http.Handle("/app2", proxy2)
    http.ListenAndServe(fmt.Sprintf(":%s", port), nil) 
}

However, whenever I run this and send a request to PROXYURL/app1, it proxies TARGET1/directory/app1. I understand that from the description of ReverseProxy, this is the intended behavior (appending the subpath of the proxy URL to the target). However, I was wondering if it is possible to map a proxy URL subpath (/app1) to another target URL without the subpath being appended to the target URL.

In summary, I want

http://proxy.com/app1 -> http://target1.com/directory

and

http://proxy.com/app2 -> http://target2.com/directory2

not (as is currently happening)

http://proxy.com/app1 -> http://target1.com/directory/app1

and

http://proxy.com/app2 -> http://target2.com/directory2/app2

Upvotes: 3

Views: 5173

Answers (1)

Chryses
Chryses

Reputation: 181

I found that by providing a custom Director function instead of using the default one provided by NewSingleHostReverseProxy() (https://golang.org/src/net/http/httputil/reverseproxy.go) , I was able to implement the behavior I wanted. I did this by setting req.URL.Path to target.Path and not appending the original req.URL.Path. Other than that, the director function was very similar to that in reverseproxy.go.

Upvotes: 5

Related Questions