Skip to content

Commit

Permalink
mailjet: refactor http client
Browse files Browse the repository at this point in the history
  • Loading branch information
EmilGeorgiev committed Nov 11, 2016
1 parent d3189e2 commit b76ec15
Show file tree
Hide file tree
Showing 11 changed files with 136 additions and 156 deletions.
1 change: 1 addition & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,4 +1,5 @@
# Compiled Object files, Static and Dynamic libs (Shared Objects)
.idea/
*.o
*.a
*.so
Expand Down
8 changes: 4 additions & 4 deletions core.go
Original file line number Diff line number Diff line change
Expand Up @@ -215,14 +215,14 @@ var NbAttempt = 5

// doRequest is called to execute the request. Authentification is set
// with the public key and the secret key specified in MailjetClient.
func (m *Client) doRequest(req *http.Request) (resp *http.Response, err error) {
func (c *httpClient) doRequest(req *http.Request) (resp *http.Response, err error) {
debugRequest(req) //DEBUG
req.SetBasicAuth(m.apiKeyPublic, m.apiKeyPrivate)
req.SetBasicAuth(c.apiKeyPublic, c.apiKeyPrivate)
for attempt := 0; attempt < NbAttempt; attempt++ {
if resp != nil {
resp.Body.Close()
}
resp, err = m.client.Do(req)
resp, err = http.DefaultClient.Do(req)
if err != nil || (resp != nil && resp.StatusCode != 500) {
break
}
Expand Down Expand Up @@ -270,4 +270,4 @@ func debugResponse(resp *http.Response) {
log.Printf("Status is: %s\n", resp.Status)
log.Printf("Header is: %s\n", resp.Header)
}
}
}
2 changes: 1 addition & 1 deletion core_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -108,4 +108,4 @@ func TestReadJsonResult(t *testing.T) {
} else {
t.Fatal("Fail to unmarshal JSON: empty res")
}
}
}
67 changes: 16 additions & 51 deletions data_api.go
Original file line number Diff line number Diff line change
@@ -1,30 +1,18 @@
package mailjet

import (
"encoding/csv"
"encoding/json"
"fmt"
"strings"
)
import "strings"

// ListData issues a GET to list the specified data resource
// and stores the result in the value pointed to by res.
// Filters can be add via functional options.
func (mj *Client) ListData(resource string, res interface{}, options ...RequestOptions) (count, total int, err error) {
func (mj *Client) ListData(resource string, resp interface{}, options ...RequestOptions) (count, total int, err error) {
url := buildDataURL(&DataRequest{SourceType: resource})
req, err := createRequest("GET", url, nil, nil, options...)
if err != nil {
return count, total, err
}
resp, err := mj.doRequest(req)
if err != nil {
return count, total, err
} else if resp == nil {
return count, total, fmt.Errorf("empty response")
}
defer resp.Body.Close()

return readJSONResult(resp.Body, res)
return mj.client.Send(req).Read(resp).Call()
}

// GetData issues a GET to view a resource specifying an id
Expand All @@ -37,22 +25,8 @@ func (mj *Client) GetData(mdr *DataRequest, res interface{}, options ...RequestO
if err != nil {
return err
}
resp, err := mj.doRequest(req)
if err != nil {
return err
} else if resp == nil {
return fmt.Errorf("empty response")
}
defer resp.Body.Close()

if resp.Header["Content-Type"] != nil {
contentType := resp.Header["Content-Type"][0]
if contentType == "application/json" {
err = json.NewDecoder(resp.Body).Decode(&res)
} else if contentType == "text/csv" {
res, err = csv.NewReader(resp.Body).ReadAll()
}
}
_, _, err = mj.client.Send(req).Read(res).Call()
return err
}

Expand All @@ -65,21 +39,15 @@ func (mj *Client) PostData(fmdr *FullDataRequest, res interface{}, options ...Re
if err != nil {
return err
}

headers := map[string]string{"Content-Type": "application/json"}
if fmdr.Info.MimeType != "" {
contentType := strings.Replace(fmdr.Info.MimeType, ":", "/", 1)
req.Header.Add("Content-Type", contentType)
} else {
req.Header.Add("Content-Type", "application/json")
headers = map[string]string{"Content-Type": contentType}
}
resp, err := mj.doRequest(req)
if err != nil {
return err
} else if resp == nil {
return fmt.Errorf("empty response")
}
defer resp.Body.Close()

return json.NewDecoder(resp.Body).Decode(&res)
_, _, err = mj.client.Send(req).With(headers).Read(res).Call()
return err
}

// PutData is used to update a data resource.
Expand All @@ -92,25 +60,22 @@ func (mj *Client) PutData(fmr *FullDataRequest, onlyFields []string, options ...
if err != nil {
return err
}
req.Header.Add("Content-Type", "application/json")
resp, err := mj.doRequest(req)
if resp != nil {
resp.Body.Close()
}

headers := map[string]string{"Content-Type": "application/json"}
_, _, err = mj.client.Send(req).With(headers).Call()

return err
}

// DeleteData is used to delete a data resource.
func (mj *Client) DeleteData(mdr *DataRequest) (err error) {
url := buildDataURL(mdr)
r, err := createRequest("DELETE", url, nil, nil)
req, err := createRequest("DELETE", url, nil, nil)
if err != nil {
return err
}
resp, err := mj.doRequest(r)
if resp != nil {
resp.Body.Close()
}

_, _, err = mj.client.Send(req).Call()

return err
}
3 changes: 2 additions & 1 deletion example_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,9 +2,10 @@ package mailjet

import (
"fmt"
"github.com/mailjet/mailjet-apiv3-go/resources"
"net/textproto"
"os"

"github.com/mailjet/mailjet-apiv3-go/resources"
)

func ExampleMailjetClient_List() {
Expand Down
70 changes: 70 additions & 0 deletions http.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,70 @@
package mailjet

import (
"encoding/csv"
"fmt"
"net/http"
)

type httpClient struct {
apiKeyPublic string
apiKeyPrivate string
headers map[string]string
request *http.Request
response interface{}
}

// APIKeyPublic returns the public key.
func (c *httpClient) APIKeyPublic() string {
return c.apiKeyPublic
}

// APIKeyPrivate returns the secret key.
func (c *httpClient) APIKeyPrivate() string {
return c.apiKeyPrivate
}

func (c *httpClient) Send(req *http.Request) *httpClient {
c.request = req
return c
}

func (c *httpClient) With(headers map[string]string) *httpClient {
c.headers = headers
return c
}

func (c *httpClient) Read(response interface{}) *httpClient {
c.response = response
return c
}

func (c *httpClient) Call() (count, total int, err error) {
for key, value := range c.headers {
c.request.Header.Add(key, value)
}

resp, err := c.doRequest(c.request)
if resp != nil {
defer resp.Body.Close()
}

if err != nil {
return count, total, err
} else if resp == nil {
return count, total, fmt.Errorf("empty response")
}

if c.response != nil {
if resp.Header["Content-Type"] != nil {
contentType := resp.Header["Content-Type"][0]
if contentType == "application/json" {
return readJSONResult(resp.Body, c.response)
} else if contentType == "text/csv" {
c.response, err = csv.NewReader(resp.Body).ReadAll()
}
}
}

return count, total, err
}
Loading

0 comments on commit b76ec15

Please sign in to comment.