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

View file

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

View file

@ -2,7 +2,10 @@ package seclient
import ( import (
"context" "context"
"encoding/json"
"fmt" "fmt"
"io"
"io/ioutil"
"math/rand" "math/rand"
"net/http" "net/http"
"net/http/cookiejar" "net/http/cookiejar"
@ -17,6 +20,7 @@ const (
ANON_EMAIL_LOCALPART_BYTES = 32 ANON_EMAIL_LOCALPART_BYTES = 32
ANON_PASSWORD_BYTES = 20 ANON_PASSWORD_BYTES = 20
DEVICE_ID_BYTES = 20 DEVICE_ID_BYTES = 20
READ_LIMIT int64 = 128 * 1024
) )
type SEEndpoints struct { 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("Content-Type", "application/x-www-form-urlencoded")
req.Header.Set("Accept", "application/json") req.Header.Set("Accept", "application/json")
_, err = c.HttpClient.Do(req) resp, err := c.HttpClient.Do(req)
// TODO: handle response 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 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("SE-Operating-System", c.Settings.OperatingSystem)
req.Header.Set("User-Agent", c.Settings.UserAgent) 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()
}