Golang gin代理处理svelte前端和Golang API

huangapple go评论104阅读模式
英文:

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)

huangapple
  • 本文由 发表于 2021年6月2日 14:25:47
  • 转载请务必保留本文链接:https://go.coder-hub.com/67799952.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定