137 lines
2.7 KiB
Go
137 lines
2.7 KiB
Go
package main
|
|
|
|
import (
|
|
"io/ioutil"
|
|
"log"
|
|
"os"
|
|
"path/filepath"
|
|
"strings"
|
|
|
|
"gopkg.in/yaml.v2"
|
|
)
|
|
|
|
// Config 结构体用于解析yaml配置文件
|
|
type Config struct {
|
|
Host string `yaml:"Host"`
|
|
Port int `yaml:"Port"`
|
|
}
|
|
|
|
// Result 结构体用于存储解析结果
|
|
type Result struct {
|
|
FolderName string
|
|
Host string
|
|
Port int
|
|
PrefixRoute map[string]bool
|
|
}
|
|
|
|
// GetZeroInfo 遍历指定目录,并解析相关信息
|
|
func GetZeroInfo(rootDir string) (results []*Result) {
|
|
entries, err := ioutil.ReadDir(rootDir)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
for _, entry := range entries {
|
|
// 只处理目录类型
|
|
if entry.IsDir() {
|
|
result, err := findFoldersAndExtractInfo(rootDir, entry)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
results = append(results, result)
|
|
}
|
|
}
|
|
|
|
return
|
|
}
|
|
|
|
// findFoldersAndExtractInfo 查找目录并提取信息
|
|
func findFoldersAndExtractInfo(rootDir string, entry os.FileInfo) (*Result, error) {
|
|
var result *Result
|
|
|
|
folderName := entry.Name()
|
|
path := filepath.Join(rootDir, folderName)
|
|
|
|
err := filepath.Walk(path, func(path string, info os.FileInfo, err error) error {
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 跳过非目录类型
|
|
if !info.IsDir() {
|
|
return nil
|
|
}
|
|
|
|
relPath, err := filepath.Rel(path, path)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 跳过非当前目录的子目录
|
|
if strings.Contains(relPath, string(os.PathSeparator)) {
|
|
return filepath.SkipDir
|
|
}
|
|
|
|
// 读取配置文件
|
|
configPath := filepath.Join(path, "etc", folderName+".yaml")
|
|
routesPath := filepath.Join(path, "internal", "handler", "routes.go")
|
|
|
|
configContent, err := ioutil.ReadFile(configPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
var config Config
|
|
err = yaml.Unmarshal(configContent, &config)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
// 读取路由文件
|
|
routesContent, err := ioutil.ReadFile(routesPath)
|
|
if err != nil {
|
|
return err
|
|
}
|
|
|
|
PrefixRoute := extractPrefixRouteValues(string(routesContent))
|
|
|
|
// 构建结果
|
|
result = &Result{
|
|
FolderName: folderName,
|
|
Host: config.Host,
|
|
Port: config.Port,
|
|
PrefixRoute: PrefixRoute,
|
|
}
|
|
|
|
return filepath.SkipDir
|
|
})
|
|
|
|
if err != nil {
|
|
return nil, err
|
|
}
|
|
|
|
return result, nil
|
|
}
|
|
|
|
// extractPrefixRouteValues 提取路由前缀
|
|
func extractPrefixRouteValues(content string) map[string]bool {
|
|
lines := strings.Split(content, "\n")
|
|
var prefixPath map[string]bool = make(map[string]bool)
|
|
|
|
for _, line := range lines {
|
|
// 查找包含 "Path:" 的行
|
|
if strings.Contains(line, "Path:") {
|
|
path := strings.TrimSpace(strings.TrimPrefix(line, "Path:"))
|
|
paths := strings.Split(strings.Trim(path, `"`), "/")
|
|
path1 := "/" + paths[1] + "/" + paths[2]
|
|
|
|
if _, ok := prefixPath[path1]; !ok {
|
|
prefixPath[path1] = true
|
|
}
|
|
}
|
|
}
|
|
|
|
return prefixPath
|
|
}
|