Pages

Monday, 24 July 2023

A tip to switch between embed FS and OS FS freely in Golang

 Why embed FS?

Go's embed FS is one of the most exicting features for me. Embeding static files (js, css. html) into a single binary makes application deployment just copying a single file.

Embed FS is not convenient during deveopment

Embed FS is readonly, so when debugging go app, those static files cannot be updated without reruning your go app. This is very bad for debugging and editing those static files.

Solution: use embed FS in production; use OS FS in development

By a simple flag we can switch between embed FS and OS FS.

$ tree
.
├── go.mod
├── main.go
└── ui
    ├── index.html
    ├── index.js
    └── main.css


$ cat main.go
package main

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

//go:embed ui
var UI embed.FS

func main() {
        var isProd bool // if in production mode
        flag.BoolVar(&isProd, "isProd", false, "is in production mode")
        flag.Parse()

        if isProd {
                // embed FS is used in  prod mode
                uiRoot, err := fs.Sub(UI, "ui")
                if err != nil {
                        log.Fatal(err)
                }

                http.Handle("/", http.FileServer(http.FS(uiRoot)))
        } else {
                // OS file system is used in development mode
                http.Handle("/", http.FileServer(http.Dir("./ui")))
        }

        log.Fatal(http.ListenAndServe("0.0.0.0:8080", nil))
}

By default, it's running in dev mode, so you can edit static files as you like and see the update right away without rerunning your app.

When runing it in production , just "yourapp -isProd=true".

No comments:

Post a Comment