Learn about Go Embed and how it helps with portability
Go Embed was introduced in Go 1.16, so it's been out for a little while now. It lets you bundle static files like text, HTML or images directly into your binary. This means you don't need to do separate file reads at runtime, and all of the things you need are actually inside your binary, which makes your whole application a lot more portable. So let's see why Go Embed is useful.
So the first thing I'm going to do is I'm going to make a new file, and I'm just going to call it "message.txt". Let's go back to main, and let's write a little bit of code. Okay, perfect. Let's run this first to see if it works, and then we can talk about what it does.
Look at that, it prints "Hello from Matt". So you'll notice here, this comment here, or we call this a directive in Go. And what I'm saying is take the contents of "message.txt" and store it in my string variable here called "message", and then I can simply print it out. Now what if you want to embed multiple files? You can do this by embedding a file system instead.
So what I'm going to do is I'm going to change this to be "messages", and I'm going to do "embed.fs", and I'm going to put this as "message" and "message1.txt". My IDE has been really helpful here in telling me that "message1.txt" doesn't exist. So let's duplicate this, update the message, and go back to here.
So now what we can do is we have embedded the whole file system, so we can do things like this. Let's run it and see if this works. And look at that. We can now read everything inside of this file system that we've marked as embedded, like this. Now let's look at a more practical use case for this. This is really useful for... OK, so this is a useful toy example, which shows you what embedding can do. But let's look at a more useful use case. So I'm just going to paste some code that I wrote earlier.
And let's create "index.html". Let's run it and see if it works. I need to make a change here. And if we go to "localhost 8080", you can see that my website is rendered. So as you can see, I've managed to serve an entire website from my binary. There's no external files needed after compilation.
So as you can see, embedding data into your binary can be really useful, really powerful, and is one of the few features of Go that feels a little bit like magic that you might see in other ecosystems. It's actually quite rare to see in the Go ecosystem. But I hope you find this useful, and I look forward to seeing what you do with Go Embed.