Use main listen for nginx

This commit is contained in:
Pim van Pelt
2025-08-25 11:41:16 +02:00
parent 92e3f6baac
commit c9c1e81619
2 changed files with 39 additions and 4 deletions

View File

@@ -10,8 +10,8 @@ import (
)
const nginxTemplate = `server {
listen 8080;
listen [::]:8080;
listen {{.ListenPort}};
listen [::]:{{.ListenPort}};
# Replace with your actual domain(s)
server_name {{.MonitoringHost}};
@@ -70,13 +70,23 @@ const nginxTemplate = `server {
`
type NginxTemplateData struct {
MonitoringHost string
MonitoringHost string
LocalDirectory string
ListenPort string
}
func generateNginx(yamlFile string) {
config := loadConfig(yamlFile)
// Extract port from first listen address
listenPort := "8080" // fallback default
if len(config.Listen) > 0 {
port := extractPort(config.Listen[0])
if port != "" {
listenPort = port
}
}
for _, log := range config.Logs {
// Extract hostname from monitoring prefix
hostname, err := extractHostname(log.MonitoringPrefix)
@@ -87,8 +97,9 @@ func generateNginx(yamlFile string) {
// Create template data
data := NginxTemplateData{
MonitoringHost: hostname,
MonitoringHost: hostname,
LocalDirectory: log.LocalDirectory,
ListenPort: listenPort,
}
// Parse and execute template
@@ -121,6 +132,25 @@ func generateNginx(yamlFile string) {
}
}
func extractPort(listenAddr string) string {
// Handle common listen address formats:
// ":8080" -> "8080"
// "localhost:8080" -> "8080"
// "[::]:8080" -> "8080"
if strings.HasPrefix(listenAddr, ":") {
return listenAddr[1:] // Remove the leading ":"
}
// For addresses with host:port format
if strings.Contains(listenAddr, ":") {
parts := strings.Split(listenAddr, ":")
return parts[len(parts)-1] // Return the last part (port)
}
return ""
}
func extractHostname(urlStr string) (string, error) {
if !strings.HasPrefix(urlStr, "http://") && !strings.HasPrefix(urlStr, "https://") {
urlStr = "https://" + urlStr