DEV Community

loading...

Working with Go Embed

Aditya
Updated on ・2 min read

With the release of Go-1.16, Go released a core package called embed. This post will cover the various ways we can use Go Embed and build applications with ease.

Building a Web Application

Golang being a versatile language, it is very much capable of being used to write server for web applications.
We would be using React as the front-end for this and expose the full scale web application from a single Golang binary.

App Structure
image

In the Project root, we maintain the server in the root and expose the client from within the client folder.

main.go --> main driver of the application from which the server is started and the client is exposed statically

main.go

//go:embed client/build
var content embed.FS
Enter fullscreen mode Exit fullscreen mode

Golang 1.16 comes with the go:embed directive.
We just specify the target folder which we want to map to our server.

Exposing the app on the root of your running server

mux.HandleFunc("/", rootHandler)
Enter fullscreen mode Exit fullscreen mode

Create a function called rootHandler.
rootHandler exposes the static content onto the / endpoint.

func rootHandler(w http.ResponseWriter, req *http.Request) {
    upath := req.URL.Path
    if !strings.HasPrefix(upath, "/") {
        upath = "/" + upath
        req.URL.Path = upath
    }
    upath = path.Clean(upath)
    fsys := fs.FS(content)
    contentStatic, _ := fs.Sub(fsys, "client/build")
    if _, err := contentStatic.Open(strings.TrimLeft(upath, "/")); err != nil {
        req.URL.Path = "/"
    }
    http.FileServer(http.FS(contentStatic)).ServeHTTP(w, req)
}
Enter fullscreen mode Exit fullscreen mode

This is enough for exposing the static build of the react app via a Golang server.

Building the Golang Binary

GOOS=linux go build -o server main.go
Enter fullscreen mode Exit fullscreen mode

Running the server binary

./server
Enter fullscreen mode Exit fullscreen mode

Now once this is tested on a localhost, we can build a Docker Image for this WebApp.

Dockerfile

FROM alpine:latest

ADD server /opt/app/

WORKDIR /opt/app/

RUN ls -lrt

EXPOSE 9191

CMD ["./server"]
Enter fullscreen mode Exit fullscreen mode

Docker Build and Run Command

docker build -t server:v1.0 .
docker run -d -p 9000:9191 server:v1.0
Enter fullscreen mode Exit fullscreen mode

Overall we can say that introduction of go:embed has made some previous complicated tasks much simpler. We can now expose a full fledged web application with a single golang binary and expose it on any platform.

To read more about go:emebed use the following references:

Discussion (0)