This commit is contained in:
Vladislav Yarmak 2021-03-25 20:29:37 +02:00
parent 67206a164c
commit fa5f109285
3 changed files with 48 additions and 10 deletions

View file

@ -6,9 +6,13 @@ import (
"strconv"
)
const (
SE_STATUS_OK int64 = 0
)
type SEStatusPair struct {
StatusCode int64
Status string
Code int64
Message string
}
func (p *SEStatusPair) UnmarshalJSON(b []byte) error {
@ -34,8 +38,13 @@ func (p *SEStatusPair) UnmarshalJSON(b []byte) error {
}
*p = SEStatusPair{
StatusCode: code,
Status: strStatus,
Code: code,
Message: strStatus,
}
return nil
}
type SERegisterSubscriberResponse struct {
Data interface{} `json:"data"`
Status SEStatusPair `json:"return_code"`
}

View file

@ -1,9 +1,9 @@
package seclient
import (
"io"
"encoding/base64"
"encoding/hex"
"io"
"strings"
)

View file

@ -2,7 +2,10 @@ package seclient
import (
"context"
"encoding/json"
"fmt"
"io"
"io/ioutil"
"math/rand"
"net/http"
"net/http/cookiejar"
@ -17,6 +20,7 @@ const (
ANON_EMAIL_LOCALPART_BYTES = 32
ANON_PASSWORD_BYTES = 20
DEVICE_ID_BYTES = 20
READ_LIMIT int64 = 128 * 1024
)
type SEEndpoints struct {
@ -135,8 +139,23 @@ func (c *SEClient) Register(ctx context.Context) error {
req.Header.Set("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json")
_, err = c.HttpClient.Do(req)
// TODO: handle response
resp, err := c.HttpClient.Do(req)
if err != nil {
return err
}
decoder := json.NewDecoder(resp.Body)
var regRes SERegisterSubscriberResponse
err = decoder.Decode(&regRes)
cleanupBody(resp.Body)
if err != nil {
return err
}
if regRes.Status.Code != SE_STATUS_OK {
return fmt.Errorf("API responded with error message: code=%d, msg=\"%s\"",
regRes.Status.Code, regRes.Status.Message)
}
return nil
}
@ -145,3 +164,13 @@ func (c *SEClient) populateRequest(req *http.Request) {
req.Header.Set("SE-Operating-System", c.Settings.OperatingSystem)
req.Header.Set("User-Agent", c.Settings.UserAgent)
}
// Does cleanup of HTTP response in order to make it reusable by keep-alive
// logic of HTTP client
func cleanupBody(body io.ReadCloser) {
io.Copy(io.Discard, io.LimitedReader{
R: resp.Body,
N: READ_LIMIT,
})
body.Close()
}