gin icon indicating copy to clipboard operation
gin copied to clipboard

[question] How to reverse proxy a web and the static url in it

Open WROIATE opened this issue 5 years ago • 3 comments

Description

I have found the related issues:   #1714   #686 And try to use the code in the issue, but I got the 404 error when the web broswer get the remote web static file with proxy, how to solve it?

How to reproduce

r.GET("/test/*proxyPath", ReverseProxy())
...
func ReverseProxy() gin.HandlerFunc {

	target := "http://192.168.1.102:8081"
	return func(c *gin.Context) {
		remote, err := url.Parse(target)
		if err != nil {
			panic(err)
		}
		director := func(req *http.Request) {
			req.URL.Scheme = remote.Scheme
			req.URL.Host = remote.Host
			req.URL.Path = remote.Path
		}
		proxy := &httputil.ReverseProxy{Director: director}
		proxy.ServeHTTP(c.Writer, c.Request)
	}
}

Expectations

[GIN] 2020/07/22 - 00:00:00| 200 |    8.365956ms |   192.168.1.233 | GET      "/test/"
[GIN] 2020/07/22 - 00:00:00| 200 |       23.26µs |   192.168.1.233 | GET      "/test/myfile"

Actual result

[GIN] 2020/07/22 - 00:00:00| 200 |    8.365956ms |   192.168.1.233 | GET      "/test/"
[GIN] 2020/07/22 - 00:00:00| 404 |       23.26µs |   192.168.1.233 | GET      "/myfile"

WROIATE avatar Jul 21 '20 17:07 WROIATE

Hello, i've the same issue on my side. Did you find something new ?

Wariie avatar Feb 16 '21 17:02 Wariie

package main

import (
	"net/http"
	"net/http/httputil"
	"net/url"

	"github.com/gin-gonic/gin"
)

func main() {
	r := gin.Default()
	r.GET("/test/*proxyPath", ReverseProxy())
	r.Run(":8080")
}

func ReverseProxy() gin.HandlerFunc {
	target := "http://192.168.1.102:8081"
	return func(c *gin.Context) {
		// Extract the wildcard part of the original path
		proxyPath := c.Param("proxyPath")

		remote, err := url.Parse(target)
		if err != nil {
			panic(err)
		}

		// Modify the Director function to include the wildcard path
		director := func(req *http.Request) {
			req.URL.Scheme = remote.Scheme
			req.URL.Host = remote.Host
			req.URL.Path = remote.Path + "/" + proxyPath // Append the wildcard path
		}

		proxy := &httputil.ReverseProxy{Director: director}
		proxy.ServeHTTP(c.Writer, c.Request)
	}
} ```
That one has working on me

Kamukage3e avatar Dec 18 '23 10:12 Kamukage3e

@manucorporat Can we close this issue?

Kamukage3e avatar Dec 18 '23 10:12 Kamukage3e