Golang read file into string or variable: os.ReadFile, embed, Open

Golang read file into string and read file golang: os.ReadFile for golang read file to string, go read file to string and []byte, //go:embed for build-time content, os.Open with io.ReadAll; notes for golang read from file and large files.

Published

Updated

Read time 3 min read

Reviewed byDeepak Prasad

Golang read file into string or variable: os.ReadFile, embed, Open

If you want to golang read file into string, golang read file to string, or more generally golang read file content into a variable, modern Go starts with os.ReadFile. Searches like golang readfile, read from file golang, or go read file to string all map to the same few patterns: whole file in memory ([]byte or string), compile-time embedding with //go:embed, or streaming with os.Open and io.ReadAll. For timeouts or cancellation, see read file with timeout in Go; for more patterns, see ways to read a file in Go.

Tested with Go 1.24 on Linux.

NOTE
Prefer streaming or line-by-line reads for very large files; loading multi-gigabyte files into one string can exhaust memory.

Quick lab: a tiny text file

From an empty folder you can reproduce the examples:

text
$ mkdir demo && cd demo && go mod init example.com/demo
$ printf 'Hello from GoLinuxCloud\n' > myFile.txt
$ cat myFile.txt
Hello from GoLinuxCloud

The snippets below assume myFile.txt sits next to main.go in that module.


os.ReadFile reads the whole file and returns []byte plus an error. That is the usual answer for golang read file as string at runtime:

go
package main

import (
	"fmt"
	"os"
)

func main() {
	b, err := os.ReadFile("myFile.txt")
	if err != nil {
		fmt.Fprintln(os.Stderr, "read:", err)
		os.Exit(1)
	}
	s := string(b)
	fmt.Print(s)
}

You should see Hello from GoLinuxCloud followed by a newline. This replaces the older ioutil.ReadFile pattern; ioutil is deprecated since Go 1.16.


Same data as []byte (golang read file into variable)

If you keep []byte, you avoid an extra copy until you need a string:

go
package main

import (
	"fmt"
	"os"
)

func main() {
	data, err := os.ReadFile("myFile.txt")
	if err != nil {
		fmt.Fprintln(os.Stderr, "read:", err)
		os.Exit(1)
	}
	fmt.Printf("len=%d\n", len(data))
}

You should see a length matching the file size (including the newline).


os.Open with io.ReadAll (streams, custom flags)

When you need an io.Reader—for example to reuse helpers that expect a stream—open the file and read it all:

go
package main

import (
	"fmt"
	"io"
	"os"
)

func main() {
	f, err := os.Open("myFile.txt")
	if err != nil {
		fmt.Fprintln(os.Stderr, "open:", err)
		os.Exit(1)
	}
	defer f.Close()

	b, err := io.ReadAll(f)
	if err != nil {
		fmt.Fprintln(os.Stderr, "read:", err)
		os.Exit(1)
	}
	fmt.Print(string(b))
}

You should see the same greeting text. Always defer f.Close() (or handle errors from Close in strict code paths).


Build-time file content: //go:embed

For golang build implement file content to variable at compile time, use the embed directive. The file path is relative to the source file containing the directive; the variable must be at package level.

go
package main

import (
	_ "embed"
	"fmt"
)

//go:embed myFile.txt
var content string

func main() {
	fmt.Print(content)
}
Output

You should see the file text without distributing myFile.txt next to the binary (it is inside the executable). You can also embed as []byte or embed.FS for multiple files; import _ "embed" whenever you use the directive (see package embed).


Summary

To golang read from file into memory, use os.ReadFile and convert with string(bytes) for golang read file into string, or keep bytes for binary-safe work. Use os.Open plus io.ReadAll when you already need a file handle. Use //go:embed when file content should ship inside the binary. Avoid deprecated io/ioutil in new code. For big inputs, switch to incremental reading instead of one giant variable.


References


Frequently Asked Questions

1. How do I golang read file into string at runtime?

Use os.ReadFile(path) which returns ([]byte, error), then string(bytes) for a string, or keep []byte if you treat the file as binary; always check the error.

2. What replaced ioutil.ReadFile in Go?

os.ReadFile is the direct replacement; pair os.Open with io.ReadAll when you need a stream or partial reads instead of loading the whole file.

3. When should I use go embed instead of os.ReadFile?

Use //go:embed when the file should be baked into the binary at compile time for simpler deployment; use os.ReadFile when the path is chosen at runtime or the content changes on disk.

4. Is it safe to golang read file as string for huge logs?

Loading an entire huge file into one string or byte slice uses a lot of memory; for large inputs use bufio.Scanner or bufio.Reader line by line, or io.LimitReader.

5. How is golang build implement file content to variable different from embed?

Build-time embed fills a package-level variable during compilation; os.ReadFile reads whatever is on disk when the program runs, which is what most CLIs and servers need.
Deepak Prasad

R&D Engineer

Founder of GoLinuxCloud with more than 15 years of expertise in Linux, Python, Go, Laravel, DevOps, Kubernetes, Git, Shell scripting, OpenShift, AWS, Networking, and Security. With extensive …