[Go] Strip embed FS’s directory name

Natan
2 min readMar 22, 2021

In Go 1.16, embed package rolled out. I used to package all kinds of resources with packr. Now I can replace it with embed .

Assuming there’s a directoryasset in the project and with two subdirectories: images and webapp . In order to package these files into the binary, we can create a file asset.go inside the dir.

/asset
/images
/a.png
/b.png
/webapp
/index.js
/index.css
/index.html
/asset.go

The content of asset.go :

package asset

import (
"embed"
"github.com/gopub/wine"
)

//go:embed images webapp
var Content embed.FS

Now we can access files inside images and webapp

asset.Content.ReadFile("images/a.png")
asset.Content.ReadFile("webapp/index.html")

It’s tricky to serve a http file service, then we can embed a website inside. It’s pretty cool.

http.FileServer(http.FS(asset.Content))

However, the url would be like http://yourdomain/webapp/index.html . In most conditions, what we want is http://yourdomain/index.html . webapp is just a directory to contain all html, js, css files, which should not be present in the url path.

How to strip it?

There are two ways:

  1. Embed current directory
    As the example above is embeding a sub directory webapp , we can add a file webapp.go inside dir webapp , and…

--

--

Natan

Senior Software Engineer. Used to work with Tencent, Alibaba and Amazon.