Go Ways

How to Embed React App into Go Binary

All that is mine I carry with me

Pavel Fokin
3 min readJul 23, 2022
Go + React

Image that you have an amazing project with React app, and you want to distribute and deploy it along with you Go application.

Let’s say that it is a super cool LikeIt! project, and it allows to like a page ¯\_(ツ)_/¯.

Like It!

01 Project structure

First, lets review the project structure.

In the root of the project we have the main.go file. This is the entry point and keeps all the go code.

  • main.go — is in the root of the project and this is an entry point for our Go app.
  • /web directory keeps code and assets for the React app.
  • /web/dist is an empty directory that will keep built web assets.

For this example I‘m using Parcel to build a web part.

Project structure

02 Go “embed” package

Since go-1.16 standard library includes embed package. This package provides access to files embedded in the running Go program.

With the usage of //go:embed directive, we can initialize a variable of type string, []byte, or FS. A variable can keep content of the file or the whole directory.

For more examples check the package documentation.

Embed package

03 How to serve static files

Embed package implements FS interface, so it can be used with any package that understands file systems, including net/http, text/template, and html/template.

That means that we can use built-in http.FileServer to serve our embedded files.

04 Results

As the result we can build a Go binary that keeps all our static files.

➜  likeit git:(main) ✗ go build -o bin/likeit main.go
➜ likeit git:(main) ✗ ls -lh bin/likeit
-rwxr-xr-x 1 pavel-fokin staff 6.6M Jul 23 16:48 bin/likeit

And it can be deployed as heroku app -> likeit-click.

Full code you can find in my GitHub repo pavel-fokin/likeit.

Thank you for reading! Share you thoughts with me on LinkedIn or Twitter.

Further readings

If you like this article you can be interested in the following.

--

--