-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathparser.go
More file actions
62 lines (51 loc) · 1.03 KB
/
parser.go
File metadata and controls
62 lines (51 loc) · 1.03 KB
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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
package canarytail
import (
"encoding/json"
"fmt"
"io/ioutil"
"net/http"
"os"
"strings"
)
// Read parses a canary from a URL or a local path
func Read(url string) (Canary, error) {
if isHTTP(url) {
return readHTTP(url)
}
return readFile(url)
}
func isHTTP(url string) bool {
return strings.HasPrefix(strings.ToLower(url), "http")
}
func readFile(path string) (canary Canary, err error) {
f, err := os.Open(path)
if err != nil {
return
}
defer f.Close()
contents, err := ioutil.ReadAll(f)
if err != nil {
return
}
return readBytes(contents)
}
func readHTTP(url string) (canary Canary, err error) {
resp, err := http.Get(url)
if err != nil {
return
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
err = fmt.Errorf("Could not retrieve canary, got code %v", resp.StatusCode)
return
}
contents, err := ioutil.ReadAll(resp.Body)
if err != nil {
return
}
return readBytes(contents)
}
func readBytes(contents []byte) (canary Canary, err error) {
err = json.Unmarshal(contents, &canary)
return
}