angulargogo-gingo-uber-fx

How to cleanly mount a static filesystem with Angular and UberFx/Gin framework?


I am attempting to mount a static filesystem with the output of ng build and the Go Gin Framework. I have successfully mounted the filesystem from output of ng build; however, I have to make a GET call for every file that I wish to mount. I would like to know if there is a way to make fewer calls and/or include a whole directory with one call. Here is the output of ng-build: dist/client and my code for mounting the filesystem (I am using the uberfx framework as well) mountStaticFS. Any help would be appreciated.


Solution

  • That can be done much easier with the embed package and http.FS.

    Basically, you have three steps:

    1. Embed the files via the go:embed directive.
    2. Strip the dist/client prefix from the client files.
    3. Optionally add a different prefix path under which the files will be served.
    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)
    }
    

    With the default settings shown above, the files dist/client/* will be available under http://0.0.0.0:48080/foo/<name of file>, with 0.0.0.0 meaning all local IPv4 addresses.