Practical Use Cases
Web Application Development
Embedding Static Web Assets
//go:embed static/*
var staticFiles embed.FS
func setupWebServer() {
http.Handle("/static/",
http.StripPrefix("/static/",
http.FileServer(http.FS(staticFiles))))
}
Template Management
//go:embed templates/*.html
var templateFS embed.FS
func renderTemplates() {
tmpl, _ := template.ParseFS(templateFS, "templates/*.html")
tmpl.Execute(w, data)
}
Configuration Management
Embedded Configuration Files
//go:embed config.yaml
var configData []byte
type AppConfig struct {
Database string
Port int
}
func loadConfiguration() *AppConfig {
var config AppConfig
yaml.Unmarshal(configData, &config)
return &config
}
Embedding Help Documentation
//go:embed docs/help.txt
var helpContent string
func displayHelp() {
fmt.Println(helpContent)
}
Microservice Scenarios
graph TD
A[Embedded Resources] --> B[Configuration]
A --> C[Service Definitions]
A --> D[Static Assets]
A --> E[Documentation]
Database Migration Scripts
Embedding Migration Files
//go:embed migrations/*.sql
var migrationFS embed.FS
func runMigrations() error {
files, _ := migrationFS.ReadDir("migrations")
for _, file := range files {
content, _ := migrationFS.ReadFile(file.Name())
// Execute migration script
}
}
Internationalization Support
Embedding Language Resources
//go:embed locales/*.json
var localeFS embed.FS
func loadTranslations(lang string) map[string]string {
data, _ := localeFS.ReadFile(fmt.Sprintf("locales/%s.json", lang))
var translations map[string]string
json.Unmarshal(data, &translations)
return translations
}
Use Case Comparison
Scenario |
Embedding Approach |
Benefits |
Web Apps |
Static file embedding |
Reduced deployment complexity |
CLI Tools |
Help/documentation |
Self-contained executable |
Microservices |
Config & migration |
Simplified configuration |
Desktop Apps |
Resource bundling |
Portable application |
Advanced Embedding Patterns
Conditional Resource Loading
//go:embed config_${ENV}.yaml
var configFile []byte
func loadEnvironmentConfig() {
// Dynamically load environment-specific config
}
Security Considerations
- Avoid embedding sensitive information
- Use environment-specific configurations
- Leverage LabEx best practices for secure embedding
- Minimize embedded resource size
- Use appropriate file types
- Leverage compile-time embedding for efficiency
Recommended Practices
- Use embedding for static, rarely changing resources
- Keep embedded files small and manageable
- Consider runtime flexibility
- Test embedded resource access thoroughly