Iterate 从Reader中迭代读取主机信息
(reader io.Reader)
| 99 | |
| 100 | // Iterate 从Reader中迭代读取主机信息 |
| 101 | func Iterate(reader io.Reader) <-chan Host { |
| 102 | hostChan := make(chan Host, 100) // 带缓冲的channel |
| 103 | |
| 104 | go func() { |
| 105 | defer close(hostChan) |
| 106 | |
| 107 | scanner := bufio.NewScanner(reader) |
| 108 | for scanner.Scan() { |
| 109 | line := strings.TrimSpace(scanner.Text()) |
| 110 | |
| 111 | // 跳过空行和注释行 |
| 112 | if line == "" || strings.HasPrefix(line, "#") { |
| 113 | continue |
| 114 | } |
| 115 | |
| 116 | // 解析主机 |
| 117 | host, err := ParseHost(line) |
| 118 | if err != nil { |
| 119 | if config.Verbose { |
| 120 | printError(fmt.Sprintf("解析失败: %s - %v", line, err)) |
| 121 | } |
| 122 | continue |
| 123 | } |
| 124 | |
| 125 | // 如果是CIDR,展开所有IP |
| 126 | if host.Type == HostTypeCIDR { |
| 127 | expandCIDR(host, hostChan) |
| 128 | } else { |
| 129 | hostChan <- host |
| 130 | } |
| 131 | } |
| 132 | |
| 133 | if err := scanner.Err(); err != nil { |
| 134 | printError(fmt.Sprintf("读取输入时出错: %v", err)) |
| 135 | } |
| 136 | }() |
| 137 | |
| 138 | return hostChan |
| 139 | } |
| 140 | |
| 141 | // expandCIDR 展开CIDR为所有包含的IP地址 |
| 142 | func expandCIDR(host Host, hostChan chan<- Host) { |
nothing calls this directly
no test coverage detected