hydroxide-push/protonmail/protonmail.go

104 lines
1.9 KiB
Go
Raw Normal View History

2017-08-22 01:04:16 +03:00
// Package protonmail implements a ProtonMail API client.
package protonmail
import (
"bytes"
"encoding/json"
"io"
"net/http"
"strconv"
)
2017-08-22 11:16:20 +03:00
const Version = 3
2017-08-22 01:04:16 +03:00
const headerAPIVersion = "X-Pm-Apiversion"
type resp struct {
Code int
*apiError
}
func (r *resp) Err() error {
if err := r.apiError; err != nil {
return r.apiError
}
return nil
}
type maybeError interface {
Err() error
}
type apiError struct {
Message string `json:"Error"`
}
func (err apiError) Error() string {
return err.Message
}
// Client is a ProtonMail API client.
type Client struct {
2017-08-22 11:16:20 +03:00
RootURL string
2017-08-22 01:04:16 +03:00
AppVersion string
2017-08-22 11:16:20 +03:00
ClientID string
2017-08-22 01:04:16 +03:00
ClientSecret string
2017-08-22 11:16:20 +03:00
HTTPClient *http.Client
2017-08-22 01:04:16 +03:00
}
func (c *Client) newRequest(method, path string, body io.Reader) (*http.Request, error) {
2017-08-22 11:16:20 +03:00
req, err := http.NewRequest(method, c.RootURL+path, body)
2017-08-22 01:04:16 +03:00
if err != nil {
return nil, err
}
req.Header.Set("X-Pm-Appversion", c.AppVersion)
req.Header.Set(headerAPIVersion, strconv.Itoa(Version))
return req, nil
}
func (c *Client) newJSONRequest(method, path string, body interface{}) (*http.Request, error) {
var b bytes.Buffer
if err := json.NewEncoder(&b).Encode(body); err != nil {
return nil, err
}
2017-08-22 10:41:47 +03:00
req, err := c.newRequest(method, path, &b)
if err != nil {
return nil, err
}
req.Header.Set("Content-Type", "application/json")
return req, nil
2017-08-22 01:04:16 +03:00
}
func (c *Client) do(req *http.Request) (*http.Response, error) {
httpClient := c.HTTPClient
if httpClient == nil {
httpClient = http.DefaultClient
}
return httpClient.Do(req)
}
func (c *Client) doJSON(req *http.Request, respData interface{}) error {
2017-08-22 10:41:47 +03:00
req.Header.Set("Accept", "application/json")
2017-08-22 01:04:16 +03:00
resp, err := c.do(req)
if err != nil {
return err
}
defer resp.Body.Close()
if err := json.NewDecoder(resp.Body).Decode(respData); err != nil {
return err
}
if maybeError, ok := respData.(maybeError); ok {
if err := maybeError.Err(); err != nil {
return err
}
}
return nil
}