DEV Community

cameronldroberts
cameronldroberts

Posted on • Updated on • Originally published at cameronroberts.dev

Testing out some features from the Golang 1.16 Beta (Embedded files)

So with Go 1.16 coming out soon I figured it would be good to talk about a feature that is coming which I thought was pretty cool. This feature is included in the new embed package.

Installing Go 1.16

As of the time of writing Go 1.16 is still in beta so the steps to install it are as follows

go get golang.org/dl/go1.16rc1 
go1.16rc1 download 
Enter fullscreen mode Exit fullscreen mode

When it's out of beta you will just need to make sure you have upgraded using your usual upgrade mechanism brew upgrade go or download it.

//go:embed

The embed package coming in 1.16 allows you the ability to embed files as part of the Go binary. This is a pretty cool feature and with so many tools existing to provide this kind of functionality it’s clear that it will be popular.
Some examples are

In action

Now lets see embed in action..
Create a file called main.go and add the following code..

package main

import (
_ "embed"
"fmt"
)

//go:embed hello.txt
var message string

func main() {
    fmt.Println(message)
}
Enter fullscreen mode Exit fullscreen mode

Before we run this code we need to make sure we have a hello.txt that contains our message. This message can be whatever you like but I'm going for the trusty "Hello, World!".

Run the code with the following (if we're still in beta)

go1.16rc1 run main.go
Enter fullscreen mode Exit fullscreen mode

which should output something along the lines of

Hello, World!
Enter fullscreen mode Exit fullscreen mode

Now a more practical example may be embedding a version.txt or some kind of configuration file. Another use case may be to embed assets for a webapp.
The code to do that would look something like this.

package main

import (
    "embed"
    "net/http"
)

//go:embed assets/*
var assets embed.FS

func main() {
    fs := http.FileServer(http.FS(assets))
    http.ListenAndServe(":8080", fs)
}

Enter fullscreen mode Exit fullscreen mode

That is all for today and hopefully you enjoyed the post!

Top comments (0)