-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathsipcentric.go
More file actions
74 lines (61 loc) · 1.31 KB
/
sipcentric.go
File metadata and controls
74 lines (61 loc) · 1.31 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
63
64
65
66
67
68
69
70
71
72
73
74
package sipcentric
// http://developer.sipcentric.com
import (
"fmt"
"io"
"net/http"
)
const (
API_URL = "https://pbx.sipcentric.com/api/v1"
)
type Api struct {
Username string
Password string
}
func (api *Api) apiRequest(method string, path string, iord io.Reader) (*http.Response, error) {
// set up request
url := API_URL + path
req, err := http.NewRequest(method, url, iord)
if err != nil {
return nil, err
}
req.SetBasicAuth(api.Username, api.Password)
req.Header.Add("Content-Type", "application/json")
// make request
client := &http.Client{}
resp, err := client.Do(req)
if err != nil {
return nil, err
}
return resp, nil
}
func (api *Api) ValidateLogin() error {
// set up a HEAD request to validate auth
resp, err := api.apiRequest("HEAD", "/customers/me", nil)
if err != nil {
return err
}
defer resp.Body.Close()
// 200 = OK, other responses undocumented
// so assume != 200 is a failure
switch resp.StatusCode {
case 200: // OK
return nil
default:
err := fmt.Errorf("Login failure; %s", resp.Status)
return err
}
}
func New(username string, password string) (*Api, error) {
// new api
api := &Api{
Username: username,
Password: password,
}
// validate login credentials
if err := api.ValidateLogin(); err != nil {
return nil, err
}
// success
return api, nil
}