Your Web News in One Place

Help Webnuz

Referal links:

Sign up for GreenGeeks web hosting
May 9, 2021 07:26 am GMT

Working with Go Embed

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/buildvar content embed.FS

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)

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)}

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

Running the server binary

./server

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

Dockerfile

FROM golang:1.16.3 As build-envENV GO111MODULE=onADD server /opt/app/WORKDIR /opt/app/RUN ls -lrtEXPOSE 9191CMD ["./server"]

Docker Build and Run Command

docker build -t server:v1.0 .docker run -d -p 9000:9191 server:v1.0

Make sure to use the golang:1.16.3 image as the embed feature is available post the Golang 1.16 release.

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:


Original Link: https://dev.to/adi73/working-with-go-embed-2mh7

Share this article:    Share on Facebook
View Full Article

Dev To

An online community for sharing and discovering great ideas, having debates, and making friends

More About this Source Visit Dev To