package client import ( "crypto/tls" "errors" "io/ioutil" "net/http" "net/url" "strconv" "strings" "time" ) const ( urlPath = "/url/open" openPath = "/cmd/open" ) 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} } 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 } 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 }