登录
首页 >  Golang >  Go问答

Golang Gin 代理处理 Svelte 前端与 Golang API

来源:stackoverflow

时间:2024-02-20 18:45:21 176浏览 收藏

哈喽!今天心血来潮给大家带来了《Golang Gin 代理处理 Svelte 前端与 Golang API》,想必大家应该对Golang都不陌生吧,那么阅读本文就都不会很困难,以下内容主要涉及到,若是你正在学习Golang,千万别错过这篇文章~希望能帮助到你!

问题内容

我正在尝试使用 golang 和 gin 为我的 api 和前端编写代理。如果请求发送到除“/api”之外的任何内容,我想代理到 svelte 服务器。如果出现“/api/something”,我想在杜松子酒中处理它。目前我的代码是这样的。

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-allconflicts with the existing handle for the pathegment root in path '/*proxypath'


正确答案


您可以在r.NoRoute中mv代理功能 r.NoRoute(代理)

理论要掌握,实操不能落!以上关于《Golang Gin 代理处理 Svelte 前端与 Golang API》的详细介绍,大家都掌握了吧!如果想要继续提升自己的能力,那么就来关注golang学习网公众号吧!

声明:本文转载于:stackoverflow 如有侵犯,请联系study_golang@163.com删除
相关阅读
更多>
最新阅读
更多>
课程推荐
更多>