英文:
Golang gin proxy to handle svelte frontend and Golang api
问题
我正在尝试使用Golang和gin编写一个代理,用于我的API和前端。如果请求不是指向"/api",我想要代理到svelte服务器。如果请求是"/api/something",我想要在gin中处理它。目前我的代码如下:
func proxy(c *gin.Context) {
remote, err := url.Parse("http://localhost:3000")
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Director = func(req *http.Request) {
req.Header = c.Request.Header
req.Host = remote.Host
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.Any("/*proxyPath", proxy)
r.Run(":8080")
}
现在,如果我访问http://localhost:8080
,我可以看到我的svelte应用程序。但是,如果我想添加任何其他路由,我会收到一个错误,错误信息为panic: catch-all conflicts with existing handle for the path segment root in path '/*proxyPath'
。
英文:
I am trying to write a proxy for my api and frontend using Golang and gin. If the request goes to anything except "/api" I want to proxy to svelte server. If goes the "/api/something" I want to handle it in gin. Currently my code is like this.
func proxy(c *gin.Context) {
remote, err := url.Parse("http://localhost:3000")
if err != nil {
panic(err)
}
proxy := httputil.NewSingleHostReverseProxy(remote)
proxy.Director = func(req *http.Request) {
req.Header = c.Request.Header
req.Host = remote.Host
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.Any("/*proxyPath", proxy)
r.Run(":8080")
}
Now if I go to http://localhost:8080
I am seeing my svelte app. But if a want to add any other route I get an error saying panic: catch-all conflicts with existing handle for the path segment root in path '/*proxyPath'
答案1
得分: 1
你可以将代理函数移动到 r.NoRoute
中。
r.NoRoute(proxy)
英文:
You can mv proxy func in r.NoRoute
r.NoRoute(proxy)
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论