Movatterモバイル変換


[0]ホーム

URL:


embed

packagestandard library
go1.25.4Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Nov 5, 2025 License:BSD-3-ClauseImports:6Imported by:73,798

Details

Repository

cs.opensource.google/go/go

Links

Documentation

Overview

Package embed provides access to files embedded in the running Go program.

Go source files that import "embed" can use the //go:embed directiveto initialize a variable of type string, []byte, orFS with the contents offiles read from the package directory or subdirectories at compile time.

For example, here are three ways to embed a file named hello.txtand then print its contents at run time.

Embedding one file into a string:

import _ "embed"//go:embed hello.txtvar s stringprint(s)

Embedding one file into a slice of bytes:

import _ "embed"//go:embed hello.txtvar b []byteprint(string(b))

Embedded one or more files into a file system:

import "embed"//go:embed hello.txtvar f embed.FSdata, _ := f.ReadFile("hello.txt")print(string(data))

Directives

A //go:embed directive above a variable declaration specifies which files to embed,using one or more path.Match patterns.

The directive must immediately precede a line containing the declaration of a single variable.Only blank lines and ‘//’ line comments are permitted between the directive and the declaration.

The type of the variable must be a string type, or a slice of a byte type,orFS (or an alias ofFS).

For example:

package serverimport "embed"// content holds our static web server content.//go:embed image/* template/*//go:embed html/index.htmlvar content embed.FS

The Go build system will recognize the directives and arrange for the declared variable(in the example above, content) to be populated with the matching files from the file system.

The //go:embed directive accepts multiple space-separated patterns forbrevity, but it can also be repeated, to avoid very long lines when there aremany patterns. The patterns are interpreted relative to the package directorycontaining the source file. The path separator is a forward slash, even onWindows systems. Patterns may not contain ‘.’ or ‘..’ or empty path elements,nor may they begin or end with a slash. To match everything in the currentdirectory, use ‘*’ instead of ‘.’. To allow for naming files with spaces intheir names, patterns can be written as Go double-quoted or back-quotedstring literals.

If a pattern names a directory, all files in the subtree rooted at that directory areembedded (recursively), except that files with names beginning with ‘.’ or ‘_’are excluded. So the variable in the above example is almost equivalent to:

// content is our static web server content.//go:embed image template html/index.htmlvar content embed.FS

The difference is that ‘image/*’ embeds ‘image/.tempfile’ while ‘image’ does not.Neither embeds ‘image/dir/.tempfile’.

If a pattern begins with the prefix ‘all:’, then the rule for walking directories is changedto include those files beginning with ‘.’ or ‘_’. For example, ‘all:image’ embedsboth ‘image/.tempfile’ and ‘image/dir/.tempfile’.

The //go:embed directive can be used with both exported and unexported variables,depending on whether the package wants to make the data available to other packages.It can only be used with variables at package scope, not with local variables.

Patterns must not match files outside the package's module, such as ‘.git/*’, symbolic links,'vendor/', or any directories containing go.mod (these are separate modules).Patterns must not match files whose names include the special punctuation characters " * < > ? ` ' | / \ and :.Matches for empty directories are ignored. After that, each pattern in a //go:embed linemust match at least one file or non-empty directory.

If any patterns are invalid or have invalid matches, the build will fail.

Strings and Bytes

The //go:embed line for a variable of type string or []byte can have only a single pattern,and that pattern can match only a single file. The string or []byte is initialized withthe contents of that file.

The //go:embed directive requires importing "embed", even when using a string or []byte.In source files that don't refer toembed.FS, use a blank import (import _ "embed").

File Systems

For embedding a single file, a variable of type string or []byte is often best.TheFS type enables embedding a tree of files, such as a directory of staticweb server content, as in the example above.

FS implements theio/fs package'sFS interface, so it can be used with any package thatunderstands file systems, includingnet/http,text/template, andhtml/template.

For example, given the content variable in the example above, we can write:

http.Handle("/static/", http.StripPrefix("/static/", http.FileServer(http.FS(content))))template.ParseFS(content, "*.tmpl")

Tools

To support tools that analyze Go packages, the patterns found in //go:embed linesare available in “go list” output. See the EmbedPatterns, TestEmbedPatterns,and XTestEmbedPatterns fields in the “go help list” output.

Example
package mainimport ("embed""log""net/http")//go:embed internal/embedtest/testdata/*.txtvar content embed.FSfunc main() {mux := http.NewServeMux()mux.Handle("/", http.FileServer(http.FS(content)))err := http.ListenAndServe(":8080", mux)if err != nil {log.Fatal(err)}}

Index

Examples

Constants

This section is empty.

Variables

This section is empty.

Functions

This section is empty.

Types

typeFS

type FS struct {// contains filtered or unexported fields}

An FS is a read-only collection of files, usually initialized with a //go:embed directive.When declared without a //go:embed directive, an FS is an empty file system.

An FS is a read-only value, so it is safe to use from multiple goroutinessimultaneously and also safe to assign values of type FS to each other.

FS implements fs.FS, so it can be used with any package that understandsfile system interfaces, including net/http, text/template, and html/template.

See the package documentation for more details about initializing an FS.

func (FS)Open

func (fFS) Open(namestring) (fs.File,error)

Open opens the named file for reading and returns it as anfs.File.

The returned file implementsio.Seeker andio.ReaderAt when the file is not a directory.

func (FS)ReadDir

func (fFS) ReadDir(namestring) ([]fs.DirEntry,error)

ReadDir reads and returns the entire named directory.

func (FS)ReadFile

func (fFS) ReadFile(namestring) ([]byte,error)

ReadFile reads and returns the content of the named file.

Source Files

View all Source files

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f orF : Jump to
y orY : Canonical URL
go.dev uses cookies from Google to deliver and enhance the quality of its services and to analyze traffic.Learn more.

[8]ページ先頭

©2009-2025 Movatter.jp