Embedding Files in Gin
I read this quick article on dev.to that mentioned embedding static files in a Go binary. Indeed, Go did recently add this feature for static file embed. I think this is a super cool feature for a language to have. Your server, all your go code, all assets, and an entire frontend web app, all bundled up into one static binary! I love it.
However, there were a few issues with the original example snippet given in that dev.to article.
- It can only serve files in the first level of the directory
- It doesn’t work directly with Gin
- If you do take this approach in Gin directly, you have collisions with the
/*filepath
and your API routes
Eventually, after much digging, I found this issue on the library for Gin’s static middleware that helped me resolve my issue: gin-contrib/static#19.
In the end, my server entrypoint looks something like this:
func main() {
fmt.Println("Starting Server")
router := gin.Default()
router.Use(static.Serve("/", EmbedFolder(embeddedFiles, "client/build")))
router.Group("/api").GET("/hello", getHello)
router.Run("localhost:3000")
}
Last modified: