登录
首页 >  Golang >  Go问答

使用 go:embed 在 golang gin-gonic 中提供 React 静态文件,在前端 URL 上重新加载时出现 404 错误

来源:stackoverflow

时间:2024-04-30 20:00:35 369浏览 收藏

今日不肯埋头,明日何以抬头!每日一句努力自己的话哈哈~哈喽,今天我将给大家带来一篇《使用 go:embed 在 golang gin-gonic 中提供 React 静态文件,在前端 URL 上重新加载时出现 404 错误》,主要内容是讲解等等,感兴趣的朋友可以收藏或者有更好的建议在评论提出,我都会认真看的!大家一起进步,一起学习!

问题内容

我使用 gin 和 go1.17 构建了一个 go 应用程序。

我正在使用 go:embed 为使用 react 构建的 spa 应用程序提供静态内容。 (尝试 https://github.com/gin-contrib/static/issues/19 中建议的方法)。 我的前端文件位于构建文件夹中

build/index.html
build/asset-manifest.json
build/static/css/**
build/static/js/**
build/manifest.json
//go:embed build/*
var reactStatic embed.FS

type embedFileSystem struct {
    http.FileSystem
    indexes bool
}

func (e embedFileSystem) Exists(prefix string, path string) bool {
    f, err := e.Open(path)
    if err != nil {
        return false
    }

    // check if indexing is allowed
    s, _ := f.Stat()
    if s.IsDir() && !e.indexes {
        return false
    }

    return true
}

func EmbedFolder(fsEmbed embed.FS, targetPath string, index bool) static.ServeFileSystem {
    subFS, err := fs.Sub(fsEmbed, targetPath)
    if err != nil {
        panic(err)
    }
    return embedFileSystem{
        FileSystem: http.FS(subFS),
        indexes:    index,
    }
}

func main() {
    router := gin.Default()

    fs := EmbedFolder(reactStatic, "build", true)

    //Serve frontend static files
    router.Use(static.Serve("/", fs))
    /* THESE ARE MY STATIC URLs FROM THE REACT APP in FRONTEND  */
    router.Use(static.Serve("/login", fs))
    router.Use(static.Serve("/calendar", fs))

    router.NoRoute(func(c *gin.Context) {
        c.JSON(404, gin.H{
            "code": "PAGE_NOT_FOUND", "message": "Page not found",
        })
    })

    setupBaseRoutes(router, database)

    httpServerExitDone := &sync.WaitGroup{}
    httpServerExitDone.Add(1)

    srv, ln := server.StartServer(router, httpServerExitDone)

    log.Printf("Starting Server at %s", ln.Addr().String())

    quit := make(chan os.Signal)
    signal.Notify(quit, os.Interrupt)
    <-quit
    log.Println("Shutdown Server ...")

    ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
    defer cancel()
    if err := srv.Shutdown(ctx); err != nil {
        log.Fatal("Server Shutdown:", err)
    }
    log.Println("Server exiting")
}

当应用程序加载并打开页面 http://localhost:8000/ 时,它会正确打开,我可以使用react-router-dom导航到http://localhost:8000/calendar。 但是当我重新加载页面 http://localhost:8000/calendar 时,出现 404 错误。


正确答案


我对此 github issue 发表了以下评论:

我能够在我的 spa 中实现此功能,从 wwwroot 嵌入式目录提供服务,并在 noroute 处理程序中进行一些小修改,以始终返回 index.html。我最初只是想这样做:

//go:embed wwwroot
var app embed.fs
wwwroot := embedfolder(app, "wwwroot")

router.use(static.serve("/", wwwroot))
router.noroute(func(c *gin.context) {
    c.filefromfs("index.html", wwwroot)
})

但这与当路径以 /index.html 结尾时 http.serveFile function 始终执行到 "/" 的本地重定向的方式效果不佳。因此,我尝试了 "index.html",而不是 ""、"/"、"wwwroot""wwwroot/",但所有这些都失败了,因为这实际上不是嵌入式文件系统中的文件。

我的解决方案是将请求 url 重写为默认的空路径,并重新使用 static.serve 中间件,因为它可以通过手动调用来处理 "/" 路径:

wwwroot := embedFolder(app, "wwwroot")
staticServer := static.Serve("/", wwwroot)

router.Use(staticServer)
router.NoRoute(func(c *gin.Context) {
    if c.Request.Method == http.MethodGet &&
        !strings.ContainsRune(c.Request.URL.Path, '.') &&
        !strings.HasPrefix(c.Request.URL.Path, "/api/") {
        c.Request.URL.Path = "/"
        staticServer(c)
    }
})

请注意,我仅对不包含 '.' 或以我的 api 前缀开头的 get 请求执行此操作,因此对于不存在的 api 路由和文件,我仍然应该收到 404 错误,就像我使用了错误的图像路径一样。

文中关于的知识介绍,希望对你的学习有所帮助!若是受益匪浅,那就动动鼠标收藏这篇《使用 go:embed 在 golang gin-gonic 中提供 React 静态文件,在前端 URL 上重新加载时出现 404 错误》文章吧,也可关注golang学习网公众号了解相关技术文章。

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