Embed Usage Patterns
Common Embedding Scenarios
Web Application Resources
//go:embed static/css/*
//go:embed static/js/*
//go:embed static/images/*
var webAssets embed.FS
func serveStaticFiles(w http.ResponseWriter, r *http.Request) {
handler := http.FileServer(http.FS(webAssets))
handler.ServeHTTP(w, r)
}
Embedding Patterns
graph TD
A[Embed Usage] --> B[Single File]
A --> C[Multiple Files]
A --> D[Entire Directory]
A --> E[Conditional Embedding]
Configuration Management
type Config struct {
Database string
Server string
}
//go:embed configs/*.yaml
var configFiles embed.FS
func loadConfig(environment string) (Config, error) {
filename := fmt.Sprintf("configs/%s.yaml", environment)
data, err := configFiles.ReadFile(filename)
// Parse configuration
}
Embedding Strategies
Strategy |
Use Case |
Example |
Single File |
Small, static resources |
//go:embed readme.md |
Multiple Files |
Related resources |
//go:embed templates/* |
Selective Embedding |
Specific file types |
//go:embed *.json |
Templating with Embedded Files
//go:embed templates/*
var templateFiles embed.FS
func renderTemplate(name string, data interface{}) string {
tmpl, _ := template.ParseFS(templateFiles, "templates/*")
var buf bytes.Buffer
tmpl.ExecuteTemplate(&buf, name, data)
return buf.String()
}
Advanced Embedding Techniques
Multilingual Support
//go:embed locales/*.json
var localeFiles embed.FS
type Translator struct {
currentLocale string
}
func (t *Translator) Translate(key string) string {
data, _ := localeFiles.ReadFile(
fmt.Sprintf("locales/%s.json", t.currentLocale)
)
// Translation logic
}
graph LR
A[Embed Performance] --> B[Compile-Time Loading]
B --> C[No Runtime Overhead]
B --> D[Instant Access]
B --> E[Predictable Memory Usage]
Conditional Embedding
var (
//go:embed debug.log
debugLog []byte
//go:embed prod.log
prodLog []byte
)
func selectLogFile(mode string) []byte {
if mode == "debug" {
return debugLog
}
return prodLog
}
Error Handling Patterns
func safeReadEmbeddedFile(fs embed.FS, path string) ([]byte, error) {
defer func() {
if r := recover(); r != nil {
log.Println("Embedding error:", r)
}
}()
return fs.ReadFile(path)
}
Best Practices
- Use appropriate embedding modes
- Limit embedded file sizes
- Implement error handling
- Leverage LabEx for testing complex embeddings
Security Considerations
- Avoid embedding sensitive data
- Use environment-specific configurations
- Implement access controls
Conclusion
Embed usage patterns provide flexible, efficient methods for managing static resources in Go applications, enabling developers to create more compact and portable software solutions.