|
1 | 1 | package main |
2 | 2 |
|
| 3 | +import ( |
| 4 | + "bytes" |
| 5 | + "embed" |
| 6 | + "flag" |
| 7 | + "fmt" |
| 8 | + "os" |
| 9 | + "strings" |
| 10 | + "text/template" |
| 11 | + |
| 12 | + "github.com/pelletier/go-toml/v2" |
| 13 | +) |
| 14 | + |
| 15 | +// Config represents the TOML configuration structure. |
| 16 | +type Config struct { |
| 17 | + Listen int `toml:"listen"` |
| 18 | + ServerName string `toml:"server_name"` |
| 19 | + CustomKeywords []KeywordRule `toml:"custom_keywords"` |
| 20 | +} |
| 21 | + |
| 22 | +// KeywordRule maps a phrase to a destination. |
| 23 | +type KeywordRule struct { |
| 24 | + Phrase string `toml:"phrase"` |
| 25 | + Dest string `toml:"dest"` |
| 26 | +} |
| 27 | + |
| 28 | +//go:embed nginx.conf.tmpl |
| 29 | +var templateFS embed.FS |
| 30 | + |
3 | 31 | func main() { |
4 | | - println("Hello, world!") |
| 32 | + var cfgPath string |
| 33 | + flag.StringVar(&cfgPath, "config", "config.toml", "path to TOML configuration") |
| 34 | + flag.Parse() |
| 35 | + |
| 36 | + cfg, err := loadConfig(cfgPath) |
| 37 | + if err != nil { |
| 38 | + fmt.Fprintf(os.Stderr, "error loading config: %v\n", err) |
| 39 | + os.Exit(1) |
| 40 | + } |
| 41 | + |
| 42 | + out, err := generateNginx(cfg) |
| 43 | + if err != nil { |
| 44 | + fmt.Fprintf(os.Stderr, "error generating nginx config: %v\n", err) |
| 45 | + os.Exit(1) |
| 46 | + } |
| 47 | + |
| 48 | + fmt.Print(out) |
| 49 | +} |
| 50 | + |
| 51 | +func loadConfig(path string) (Config, error) { |
| 52 | + cfg := Config{Listen: 80, ServerName: "search.local"} |
| 53 | + data, err := os.ReadFile(path) |
| 54 | + if err != nil { |
| 55 | + if os.IsNotExist(err) { |
| 56 | + return cfg, nil |
| 57 | + } |
| 58 | + return cfg, err |
| 59 | + } |
| 60 | + if err := toml.Unmarshal(data, &cfg); err != nil { |
| 61 | + return cfg, err |
| 62 | + } |
| 63 | + return cfg, nil |
| 64 | +} |
| 65 | + |
| 66 | +// generateNginx assembles the nginx configuration using heuristics |
| 67 | +// and any custom keyword rules from the configuration file. |
| 68 | +func generateNginx(cfg Config) (string, error) { |
| 69 | + tmpl, err := template.New("nginx.conf.tmpl").Funcs(template.FuncMap{ |
| 70 | + "escape": escapeSpace, |
| 71 | + }).ParseFS(templateFS, "nginx.conf.tmpl") |
| 72 | + if err != nil { |
| 73 | + return "", err |
| 74 | + } |
| 75 | + |
| 76 | + var b bytes.Buffer |
| 77 | + if err := tmpl.Execute(&b, cfg); err != nil { |
| 78 | + return "", err |
| 79 | + } |
| 80 | + return b.String(), nil |
| 81 | +} |
| 82 | + |
| 83 | +func escapeSpace(s string) string { |
| 84 | + return strings.ReplaceAll(s, " ", "\\ ") |
5 | 85 | } |
0 commit comments