hoster/internals/helpers/findHostConfigs.go

70 lines
1.3 KiB
Go
Raw Normal View History

2024-08-28 12:31:17 +02:00
package helpers
import (
"bufio"
"hoster/internals/types"
"io/fs"
"os"
"regexp"
"strconv"
"strings"
"github.com/gookit/goutil/fsutil"
)
func FindHostConfigs(path string) ([]types.Project, error) {
projects := []types.Project{}
fsutil.FindInDir(path, func(filePath string, de fs.DirEntry) error {
project := types.Project{}
parseHostFile(filePath, &project)
if project.Domain != "" {
projects = append(projects, project)
}
return nil
})
return projects, nil
}
var portRegex = regexp.MustCompile(`listen\s+(\d+)`)
var serverNameRegex = regexp.MustCompile(`server_name\s+(.+);`)
func parseHostFile(filePath string, project *types.Project) error {
file, err := os.Open(filePath)
if err != nil {
return err
}
defer file.Close()
scanner := bufio.NewScanner(file)
for scanner.Scan() {
line := strings.TrimSpace(scanner.Text())
if strings.HasPrefix(line, "#") {
continue
}
if strings.HasPrefix(line, "listen ") {
port := portRegex.FindStringSubmatch(line)
project.InternalPort, err = strconv.Atoi(port[1])
if err != nil {
return err
}
}
if strings.HasPrefix(line, "server_name ") {
serverName := serverNameRegex.FindStringSubmatch(line)
project.Domain = serverName[1]
}
}
if err := scanner.Err(); err != nil {
return err
}
return nil
}