streamdeck-remote/client/client.go

96 lines
1.7 KiB
Go
Raw Normal View History

2019-05-21 04:06:20 +00:00
package client
import (
"crypto/tls"
"errors"
"io/ioutil"
"net/http"
"net/url"
"strconv"
"strings"
"time"
)
const (
urlPath = "/url/open"
2019-05-21 23:50:47 +00:00
openPath = "/cmd/open"
2019-05-21 04:06:20 +00:00
)
type RemoteClient struct {
client *http.Client
baseUrl string
token string
}
func New(host, token string) *RemoteClient {
client := &http.Client{
Timeout: 30 * time.Second,
Transport: &http.Transport{
TLSClientConfig: &tls.Config{InsecureSkipVerify: true},
},
}
return &RemoteClient{client: client, baseUrl: "https://" + host, token: token}
}
2019-05-21 23:50:47 +00:00
func (r *RemoteClient) Open(path string) error {
formData := url.Values{
"path": {path},
}
status, _, err := r.doRequest(openPath, formData)
if err != nil {
return err
} else if status != http.StatusOK {
return errors.New("invalid status: " + strconv.Itoa(status))
}
return nil
}
2019-05-21 04:06:20 +00:00
func (r *RemoteClient) OpenURL(urlStr string) error {
formData := url.Values{
"url": {urlStr},
}
status, _, err := r.doRequest(urlPath, formData)
if err != nil {
return err
} else if status != http.StatusOK {
return errors.New("invalid status: " + strconv.Itoa(status))
}
return nil
}
func (r *RemoteClient) doRequest(path string, v url.Values) (int, []byte, error) {
encoded := v.Encode()
req, err := http.NewRequest(http.MethodPost, r.baseUrl + path, strings.NewReader(encoded))
if err != nil {
return -1, nil, err
}
req.Header.Set("Authorization", "Bearer " + r.token)
req.Header.Set("Content-Length", strconv.Itoa(len(encoded)))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
res, err := r.client.Do(req)
if err != nil {
return -1, nil, err
}
defer res.Body.Close()
b, err := ioutil.ReadAll(res.Body)
if err != nil {
return -1, nil, err
}
return res.StatusCode, b, nil
}