-
Notifications
You must be signed in to change notification settings - Fork 8
/
cnamulator.go
104 lines (95 loc) · 2.13 KB
/
cnamulator.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
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
package main
import (
"bufio"
"encoding/json"
"flag"
"fmt"
"io/ioutil"
"log"
"net/http"
"os"
"strings"
)
type Opencnams struct {
Results []Opencnam `json:"results"`
}
type Opencnam struct {
Number string `json:"number"`
Name string `json:"name"`
}
func cnamReq(phonenum, sid, token string) (Opencnam, error) {
oc := Opencnam{}
resp, err := http.Get("https://api.opencnam.com/v2/phone/+" + phonenum + "?format=json&account_sid=" + sid + "&auth_token=" + token)
if err != nil {
return oc, err
}
defer resp.Body.Close()
data, err := ioutil.ReadAll(resp.Body)
if len(data) == 0 {
oc.Number = phonenum
oc.Name = "undefined"
return oc, err
}
if err != nil {
return oc, err
}
err = json.Unmarshal(data, &oc)
if err != nil {
return oc, err
}
oc.Number = strings.TrimLeft(oc.Number, "+")
return oc, nil
}
func readLines(path string) ([]string, error) {
file, err := os.Open(path)
if err != nil {
return nil, err
}
defer file.Close()
var lines []string
scanner := bufio.NewScanner(file)
for scanner.Scan() {
lines = append(lines, scanner.Text())
}
return lines, scanner.Err()
}
func main() {
phone := flag.String("phone", "", "a single phone number")
phoneFile := flag.String("file", "", "a list of phone numbers")
sid := flag.String("sid", "", "the opencnam api sid")
token := flag.String("token", "", "the opencnam api auth token")
flag.Parse()
requests := []string{}
cnams := &Opencnams{}
if (*phone != "") && (*phoneFile != "") {
log.Fatal("-phone and -file are mutually exclusive")
}
if *sid == "" {
log.Fatal("an opencnam sid is required")
}
if *token == "" {
log.Fatal("an opencnam auth token is required")
}
if *phone != "" {
requests = append(requests, *phone)
}
if *phoneFile != "" {
lines, err := readLines(*phoneFile)
if err != nil {
log.Fatalf("readLines: %s", err)
}
requests = append(requests, lines...)
}
for _, r := range requests {
result, err := cnamReq(r, *sid, *token)
if err != nil {
log.Fatal(err)
}
cnams.Results = append(cnams.Results, result)
}
j, err := json.MarshalIndent(cnams, "", " ")
if err != nil {
log.Fatal(err)
}
fmt.Println(string(j))
}