hoster/internals/helpers/findHostConfigs.go

75 lines
1.3 KiB
Go

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(`proxy_pass http://.+:(\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, "proxy_pass ") {
port := portRegex.FindStringSubmatch(line)
if len(port) == 0 {
continue
}
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
}