如何使用 Angular 和 UberFx/Gin 框架干净地挂载静态文件系统?

问题描述 投票:0回答:1

我正在尝试使用 ng build 和 Go Gin 框架的输出挂载静态文件系统。我已经从 ng build 的输出成功安装了文件系统;但是,我必须对我希望挂载的每个文件进行 GET 调用。我想知道是否有一种方法可以减少调用次数和/或通过一次调用包含整个目录。这是 ng-build 的输出:以及我用于挂载文件系统的代码(我也使用 uberfx 框架)。任何帮助将不胜感激。

angular go go-gin go-uber-fx
1个回答
0
投票

使用 embed packagehttp.FS 可以更轻松地完成此操作。

基本上,您需要三个步骤:

  1. 通过
    go:embed
    指令嵌入文件。
  2. 从客户端文件中删除
    dist/client
    前缀。
  3. 可以选择添加不同的前缀路径,在该路径下提供文件。
package main

import (
    "embed"
    "flag"
    "io/fs"
    "net/http"

    "github.com/gin-gonic/gin"
)

var (
    //go:embed dist/client
    content embed.FS

    bindAddress = flag.String("bind", ":48080", "The address to bind to.")
    pathPrefix  = flag.String("path", "/foo", "The path to serve the content.")
)

func main() {

    flag.Parse()

    var (
        router *gin.Engine = gin.Default()
        // A subset of our content.
        baseDir fs.FS
    )

    // We create a subset of our embedded content.
    // This way, we get rid of the "dist/client" prefix.
    baseDir, _ = fs.Sub(content, "dist/client")

    // Now, we can set any arbitary path to serve our content.
    router.StaticFS(*pathPrefix, http.FS(baseDir))

    router.Run(*bindAddress)
}

使用上面显示的默认设置,来自

dist/client
的文件将在
http://0.0.0.0:48080/foo
下可用,其中
0.0.0.0
表示所有本地 IPv4 地址。

© www.soinside.com 2019 - 2024. All rights reserved.