Golang gin代理处理苗条前端和Golang api
我正在尝试使用Golang和gin为我的api和前端编写代理。如果请求指向“/api”以外的任何对象,我希望代理到svelte服务器。如果“/api/something”出现,我想用杜松子酒来处理它。目前我的代码是这样的Golang gin代理处理苗条前端和Golang api,go,proxy,svelte,go-gin,Go,Proxy,Svelte,Go Gin,我正在尝试使用Golang和gin为我的api和前端编写代理。如果请求指向“/api”以外的任何对象,我希望代理到svelte服务器。如果“/api/something”出现,我想用杜松子酒来处理它。目前我的代码是这样的 func代理(c*gin.Context){ 远程,错误:=url.Parse(“http://localhost:3000") 如果错误!=零{ 恐慌(错误) } 代理:=httputil.NewSingleHostReverseProxy(远程) proxy.Directo
func代理(c*gin.Context){
远程,错误:=url.Parse(“http://localhost:3000")
如果错误!=零{
恐慌(错误)
}
代理:=httputil.NewSingleHostReverseProxy(远程)
proxy.Director=func(请求*http.Request){
req.Header=c.Request.Header
请求主机=远程主机
req.URL.Scheme=remote.Scheme
req.URL.Host=remote.Host
req.URL.Path=c.Param(“proxyPath”)
}
proxy.ServeHTTP(c.Writer,c.Request)
}
func main(){
r:=gin.Default()
r、 任何(“/*代理路径”,代理)
r、 运行(“:8080”)
}
现在如果我转到
http://localhost:8080
我看到了我的苗条应用程序。但是,如果要添加任何其他路由,我会收到一个错误,它说panic:catch all conflicts with the existing handle for the path'/*proxyPath'
您可以在r.NoRoute中使用mv proxy func
r.NoRoute(proxy)
我会使用它,但我还需要访问proxyPath变量。否则,所有内容都将转到同一地址。您可以使用代理函数中的c.Request.path.Url访问路径