diff --git a/seclient/messages.go b/seclient/messages.go index 60ace42..c6b4884 100644 --- a/seclient/messages.go +++ b/seclient/messages.go @@ -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"` +} diff --git a/seclient/randutils.go b/seclient/randutils.go index 4c02bab..d7d1f8b 100644 --- a/seclient/randutils.go +++ b/seclient/randutils.go @@ -1,9 +1,9 @@ package seclient import ( - "io" "encoding/base64" "encoding/hex" + "io" "strings" ) diff --git a/seclient/seclient.go b/seclient/seclient.go index d2d63d2..15c5da9 100644 --- a/seclient/seclient.go +++ b/seclient/seclient.go @@ -2,7 +2,10 @@ package seclient import ( "context" + "encoding/json" "fmt" + "io" + "io/ioutil" "math/rand" "net/http" "net/http/cookiejar" @@ -14,9 +17,10 @@ import ( ) const ( - ANON_EMAIL_LOCALPART_BYTES = 32 - ANON_PASSWORD_BYTES = 20 - DEVICE_ID_BYTES = 20 + 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(®Res) + 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() +}