embed package provides access to files embedded in the running Go program at compile time using the //go:embed directive.
Basic Usage
Embedding a Single File
Embedding as Bytes
Embedding Multiple Files
The embed.FS Type
Theembed.FS type implements fs.FS and provides a read-only file system.
Methods
Open(name string)- Open a file for readingReadDir(name string)- Read directory contentsReadFile(name string)- Read entire file
Practical Examples
Embedding Static Web Assets
Embedding HTML Templates
Embedding Configuration Files
Embedding SQL Migration Files
Embedding Frontend Build
Embedding Test Fixtures
Walking Embedded Directory
Directive Patterns
Single File
Multiple Files
Wildcard Patterns
Multiple Directives
Rules and Limitations
What Can Be Embedded
- Files in the same directory or subdirectories
- Files in the module containing the package
- Files must be readable at build time
What Cannot Be Embedded
- Files outside the module
- Symbolic links
- Hidden files (starting with
.or_) - Files in
testdatadirectories (unless explicitly specified)
Syntax Rules
Working with text/template
Checking for Embedded Files
Best Practices
- Organize embedded files - Keep them in dedicated directories
- Use embed.FS for multiple files - More flexible than string or []byte
- Document embedded files - Comment what files are embedded and why
- Consider binary size - Embedded files increase binary size
- Use for truly static content - Don’t embed files that change frequently
- Validate at startup - Check that required embedded files are present
- Version control embedded files - Include them in your repository
Common Use Cases
- Web applications: HTML, CSS, JavaScript files
- Configuration: Default configuration files
- Templates: Email, report, or document templates
- Assets: Images, fonts, icons
- Database migrations: SQL schema and migration files
- Documentation: Help text and user guides
- Test fixtures: Sample data for testing
- Certificates: TLS certificates and keys
Build Tags and Conditional Embedding
Performance Considerations
- Embedded files are included in the binary at compile time
- Reading is fast - no disk I/O needed
- Files are decompressed on demand
- Multiple reads of the same file are efficient
- Binary size increases by the total size of embedded files