2022-05-11 22:47:31 +00:00
|
|
|
package nginx
|
|
|
|
|
|
|
|
import (
|
2022-07-21 08:02:07 +00:00
|
|
|
"fmt"
|
2022-11-08 00:03:45 +00:00
|
|
|
"os"
|
2022-05-11 22:47:31 +00:00
|
|
|
|
2022-07-21 08:02:07 +00:00
|
|
|
"npm/internal/entity/certificate"
|
|
|
|
"npm/internal/entity/host"
|
2023-01-04 05:36:56 +00:00
|
|
|
"npm/internal/entity/upstream"
|
2022-07-21 08:02:07 +00:00
|
|
|
"npm/internal/logger"
|
2023-01-04 05:36:56 +00:00
|
|
|
"npm/internal/util"
|
2022-05-11 22:47:31 +00:00
|
|
|
|
|
|
|
"github.com/aymerick/raymond"
|
|
|
|
)
|
|
|
|
|
2022-11-08 00:03:45 +00:00
|
|
|
// TemplateData is a struct
|
2022-07-21 08:02:07 +00:00
|
|
|
type TemplateData struct {
|
|
|
|
ConfDir string
|
|
|
|
DataDir string
|
2022-11-08 00:03:45 +00:00
|
|
|
Host host.Template
|
|
|
|
Certificate certificate.Template
|
2023-01-04 05:36:56 +00:00
|
|
|
Upstream upstream.Model
|
2022-07-21 08:02:07 +00:00
|
|
|
}
|
|
|
|
|
|
|
|
func generateHostConfig(template string, data TemplateData) (string, error) {
|
2023-01-04 05:36:56 +00:00
|
|
|
logger.Debug("Rendering Template - Template: %s", template)
|
|
|
|
logger.Debug("Rendering Template - Data: %+v", data)
|
2022-07-21 08:02:07 +00:00
|
|
|
return raymond.Render(template, data)
|
2023-01-04 05:36:56 +00:00
|
|
|
|
|
|
|
// todo: apply some post processing to this config, stripe trailing whitespace from lines and then remove groups of 2+ \n's so the config looks nicer
|
2022-07-21 08:02:07 +00:00
|
|
|
}
|
2022-05-11 22:47:31 +00:00
|
|
|
|
2022-07-21 08:02:07 +00:00
|
|
|
func writeTemplate(filename, template string, data TemplateData) error {
|
|
|
|
output, err := generateHostConfig(template, data)
|
2022-05-11 22:47:31 +00:00
|
|
|
if err != nil {
|
2022-07-21 08:02:07 +00:00
|
|
|
output = fmt.Sprintf("# Template Error: %s", err.Error())
|
2022-05-11 22:47:31 +00:00
|
|
|
}
|
|
|
|
|
2022-07-21 08:02:07 +00:00
|
|
|
// Write it. This will also write an error comment if generation failed
|
|
|
|
// nolint: gosec
|
2023-01-04 05:36:56 +00:00
|
|
|
writeErr := writeConfigFile(filename, util.CleanupWhitespace(output))
|
2022-05-11 22:47:31 +00:00
|
|
|
if err != nil {
|
|
|
|
return err
|
|
|
|
}
|
2022-07-21 08:02:07 +00:00
|
|
|
return writeErr
|
|
|
|
}
|
2022-05-11 22:47:31 +00:00
|
|
|
|
2022-07-21 08:02:07 +00:00
|
|
|
func writeConfigFile(filename, content string) error {
|
|
|
|
logger.Debug("Writing %s with:\n%s", filename, content)
|
2022-05-11 22:47:31 +00:00
|
|
|
// nolint: gosec
|
2022-11-08 00:03:45 +00:00
|
|
|
return os.WriteFile(filename, []byte(content), 0644)
|
2022-05-11 22:47:31 +00:00
|
|
|
}
|