-
Notifications
You must be signed in to change notification settings - Fork 0
/
profile.go
95 lines (78 loc) · 1.81 KB
/
profile.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
package main
import (
"bytes"
"encoding/json"
"errors"
"log"
"net/http"
"github.com/batmac/nextdns_exporter/nextdns"
)
type Profile struct {
ID string `json:"id"`
Name string `json:"name"`
Role string `json:"role"`
Fingerprint string `json:"fingerprint"`
}
type Profiles struct {
Profiles []Profile `json:"data"`
}
func getProfiles(c *nextdns.Client) ([]Profile, error) {
req, err := c.Get(c.BaseURL + "profiles")
if err != nil {
log.Printf("Error: %v", err)
return nil, err
}
if req.StatusCode != 200 {
log.Printf("Error: %v", req.Status)
return nil, errors.New(req.Status)
}
defer req.Body.Close()
var content bytes.Buffer
_, err = content.ReadFrom(req.Body)
if err != nil {
log.Printf("Error: %v", err)
return nil, err
}
log.Printf("Content: %v", content.String())
var profiles Profiles
err = json.Unmarshal(content.Bytes(), &profiles)
if err != nil {
log.Printf("Error: %v", err)
return nil, err
}
if len(profiles.Profiles) == 0 {
log.Printf("Error: no profile found")
return nil, errors.New("no profile found")
}
return profiles.Profiles, nil
}
func getProfileIDs(c *nextdns.Client) ([]string, error) {
p := make([]string, 0)
profiles, err := getProfiles(c)
if err != nil {
return nil, err
}
for _, profile := range profiles {
p = append(p, profile.ID)
}
return p, nil
}
func getProfile(id string, c *http.Client) (string, error) {
req, err := c.Get("https://api.nextdns.io/profiles/" + id)
if err != nil {
log.Printf("Error: %v", err)
return "", err
}
if req.StatusCode != 200 {
log.Printf("Error: %v", req.Status)
return "", errors.New(req.Status)
}
defer req.Body.Close()
var content bytes.Buffer
_, err = content.ReadFrom(req.Body)
if err != nil {
log.Printf("Error: %v", err)
return "", err
}
return content.String(), nil
}