refactor config and nginx parsers

This commit is contained in:
2026-08-22 16:04:32 +08:00
parent a06771b708
commit 0102fa6ce9
3 changed files with 93 additions and 47 deletions
+23 -7
View File
@@ -78,44 +78,60 @@ func parseNodeSsrBlock(content []byte) (nodeSsrBlock, error) {
return nodeSsrBlock{}, errors.New("host Nginx configuration is empty")
}
lines := strings.Split(string(content), "\n")
begin, end, err := findNodeSsrMarkers(lines)
if err != nil {
return nodeSsrBlock{}, err
}
servers, err := collectNodeSsrServers(lines, begin, end)
if err != nil {
return nodeSsrBlock{}, err
}
return nodeSsrBlock{lines: lines, servers: servers}, nil
}
func findNodeSsrMarkers(lines []string) (int, int, error) {
begin, end := -1, -1
for index, line := range lines {
switch strings.TrimSpace(line) {
case nodeSsrManagedBegin:
if begin != -1 {
return nodeSsrBlock{}, errors.New("host Nginx configuration contains duplicate Node SSR upstream begin markers")
return 0, 0, errors.New("host Nginx configuration contains duplicate Node SSR upstream begin markers")
}
begin = index
case nodeSsrManagedEnd:
if end != -1 {
return nodeSsrBlock{}, errors.New("host Nginx configuration contains duplicate Node SSR upstream end markers")
return 0, 0, errors.New("host Nginx configuration contains duplicate Node SSR upstream end markers")
}
end = index
}
}
if begin == -1 || end <= begin {
return nodeSsrBlock{}, errors.New("host Nginx configuration requires one ordered Node SSR upstream marker pair")
return 0, 0, errors.New("host Nginx configuration requires one ordered Node SSR upstream marker pair")
}
return begin, end, nil
}
func collectNodeSsrServers(lines []string, begin, end int) ([]nodeSsrServer, error) {
servers := make([]nodeSsrServer, 0, 2)
seen := make(map[int]struct{}, 2)
for index := begin + 1; index < end; index++ {
server, found, err := parseNodeSsrServer(lines[index], index)
if err != nil {
return nodeSsrBlock{}, err
return nil, err
}
if !found {
continue
}
if _, exists := seen[server.port]; exists {
return nodeSsrBlock{}, fmt.Errorf("managed Node SSR upstream contains duplicate port %d", server.port)
return nil, fmt.Errorf("managed Node SSR upstream contains duplicate port %d", server.port)
}
seen[server.port] = struct{}{}
servers = append(servers, server)
}
if len(servers) != 2 {
return nodeSsrBlock{}, fmt.Errorf("managed Node SSR upstream must contain exactly two servers, got %d", len(servers))
return nil, fmt.Errorf("managed Node SSR upstream must contain exactly two servers, got %d", len(servers))
}
return nodeSsrBlock{lines: lines, servers: servers}, nil
return servers, nil
}
// parseNodeSsrServer parses one server line inside the managed Node SSR block.