Skip to content

Temporary Files and Embedding

This guide covers two important file-system concepts: working with temporary data and embedding static files into your Go binary.

1. Temporary Files and Directories

Sometimes you need a file just for a few seconds (e.g., to process an upload). Use os.CreateTemp to create a file in the OS's temporary folder with a unique name.

package main

import (
    "fmt"
    "os"
)

func main() {
    // 1. Create a temporary file
    // The "" means use the default temporary directory
    f, _ := os.CreateTemp("", "sample-*.txt")

    // 2. Clean up when finished
    defer os.Remove(f.Name())

    fmt.Println("Temp file name:", f.Name())

    // 3. Create a temporary directory
    d, _ := os.MkdirTemp("", "sampledir-*")
    defer os.RemoveAll(d)
}

2. The embed Directive

Introduced in Go 1.16, the //go:embed directive allows you to pack static files (like HTML or images) directly into your compiled .exe or binary file. This makes deployment much easier because you only have one file to share.

package main

import (
    "embed"
    "fmt"
)

// 1. Tell Go which file to embed
//go:embed folder/version.txt
var version string

// 2. You can also embed a whole folder
//go:embed static/*
var staticFiles embed.FS

func main() {
    fmt.Println("Version:", version)

    // Read a file from the embedded folder
    data, _ := staticFiles.ReadFile("static/logo.png")
    fmt.Println("Logo size:", len(data))
}

Why use Embedding?

  1. Single Binary: No more "file not found" errors on production servers. All your CSS, JS, and templates are inside the program.
  2. Security: Embedded files are read-only, preventing them from being tampered with at runtime.
  3. Speed: Accessing data from memory is faster than reading from a spinning disk or SSD.