-
Notifications
You must be signed in to change notification settings - Fork 0
/
file.go
44 lines (37 loc) · 892 Bytes
/
file.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
package ipsearch
import (
"bufio"
"fmt"
"io"
"net/http"
"os"
)
// ReadFile reads a ip cidr list file and returns a slice of strings, one for each line.
func ReadFile(filename string) ([]string, error) {
file, err := os.Open(filename)
if err != nil {
return nil, err
}
defer file.Close()
return readLines(file)
}
// ReadFileFromURL from a URL and returns a slice of strings, one for each line.
func ReadFileFromURL(url string) ([]string, error) {
resp, err := http.Get(url)
if err != nil {
return nil, err
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
return nil, fmt.Errorf("status code error: %d", resp.StatusCode)
}
return readLines(resp.Body)
}
func readLines(r io.Reader) ([]string, error) {
var lines []string
scanner := bufio.NewScanner(r)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}