Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save danawoodman/64e9c512297c48817b17277dc2728358 to your computer and use it in GitHub Desktop.
Save danawoodman/64e9c512297c48817b17277dc2728358 to your computer and use it in GitHub Desktop.
Serving embedded static files with Echo (Golang)

Serving embedded static files with Echo (Golang)

For a project I'm working on, I need to ship a single server binary with all static files embedded and use that for the frontend of the server. The backend has a variety of routes which the frontend calls.

The frontend is a SvelteKit static app built to ./frontend/build. Here is the Echo configuration to get these files serving at the root of the web server:

package main

import (
  "embed"
	"io/fs"
	"os"

	"github.com/labstack/echo/v4"
	"github.com/labstack/echo/v4/middleware"
)

//go:embed frontend/build/*
var staticFiles embed.FS


func main {
	e := echo.New()

	// Middleware
	e.Use(middleware.Logger())
	e.Use(middleware.Recover())

	// Route handlers
	e.GET("/some/:path", someHandler)
	e.GET("/another", anotherHandler)
  
	// Serve embedded static files found at ./frontend/build
	e.StaticFS("/", echo.MustSubFS(staticFiles, "frontend/build"))

	e.Logger.Fatal(e.Start(":8888"))
}

The two big takeaways here is to use frontend/build/* with the asterix; if you don't have an asterix (and instead do frontend/build, Golang will ignore the _app folder that SvelteKit bundles the app within the build directory because by default go ignores any file or folder starting wtih . or _.

The second takeaway is to use the StaticFS method to mount the embedded filesystem at the root route so any fall-through requests will get matched with the static files, if present.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment