gin-gonic / gin

Gin is a HTTP web framework written in Go (Golang). It features a Martini-like API with much better performance -- up to 40 times faster. If you need smashing performance, get yourself some Gin.
https://gin-gonic.com/
MIT License
78.96k stars 8.02k forks source link

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

Open WROIATE opened 4 years ago

WROIATE commented 4 years ago

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"
Wariie commented 3 years ago

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

Kamukage3e commented 11 months ago

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 commented 11 months ago

@manucorporat Can we close this issue?