gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-12-04 17:18:28 34 4
gpt4 key购买 nike

我正在尝试使用 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'

最佳答案

你可以在 r.NoRoute 中使用 mv proxy funcr.NoRoute(代理)

关于Golang gin 代理处理 svelte 前端和 Golang api,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/67799952/

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com