How to embed the content of a file to a variable in Golang

A quick look at golang embed package

In this article, we were talking about how to deal with a large file in Golang. But have you ever seen yourself in a situation that just wanted to read a file and load its entire content to a variable and work with it? I have been in the same situation a lot. For example for reading a specific configuration from a file and somehow, this file is always there! I mean you know that you need that file to build/run your application. Let's talk about it in code, Imagine we have a file named config.txt with the content below:

I am a file that you need me ;)

And wanted to read this file.

package main

import (
    "fmt"
    "io/ioutil"
    "log"
    "os"
)

func main() {
    file, err := os.Open("config.txt")
    if err != nil {
        log.Fatalf("missing config file: %v", err)
    }
    content, err := ioutil.ReadAll(file)
    if err != nil {
        log.Fatalf("could not read config file: %v", err)
    }
    fmt.Println(string(content))
}
// output: I am a file that you need me ;)

if the code above sounds familiar to you, I have great news for you, Go offers a better, nice, and shorter way to do that. There is a package called embed do all of it for you in a single line. All you need is just pass the file path in a directive above your variable

package main

import (
    _ "embed"
    "fmt"
)

//go:embed config.txt
var content string

func main() {
    fmt.Print(content)
}
// output: I am a file that you need me ;)

That's it! you have the content of the file in the content variable! do you need to have it in []byte? you just need to change your variable type.

package main

import (
    _ "embed"
    "fmt"
)

//go:embed config.txt
var content []byte

func main() {
    fmt.Print(content)
}
// output: [73 32 97 109 32 97 32 102 105 108 101 32 116 104 97 116 32 121 111 117 32 110 101 101 100 32 109 101 32 59 41]