Skip to content

Commit

Permalink
Fix compatibility with Mailgun API protocol bug.
Browse files Browse the repository at this point in the history
Sometimes, bounce API returns status codes as strings, and other times
as integers.  This violates mailgun-go's interface conventions,
preventing us from using reflection to figure out how to automatically
decode the JSON response.

This introduces a BREAKING CHANGE to the Mailgun-go API.  However, it's
required to be enable compatbility with the existing API.

Fixes #20
  • Loading branch information
Samuel A. Falvo II committed May 27, 2015
1 parent e5be78d commit e83dcc3
Show file tree
Hide file tree
Showing 2 changed files with 61 additions and 4 deletions.
22 changes: 18 additions & 4 deletions bounces.go
Expand Up @@ -12,10 +12,10 @@ import (
// while Error provides a human readable reason why.
// CreatedAt provides the time at which Mailgun detected the bounce.
type Bounce struct {
CreatedAt string `json:"created_at"`
Code string `json:"code"`
Address string `json:"address"`
Error string `json:"error"`
CreatedAt string `json:"created_at"`
code interface{} `json:"code"`
Address string `json:"address"`
Error string `json:"error"`
}

type bounceEnvelope struct {
Expand All @@ -33,6 +33,20 @@ func (i Bounce) GetCreatedAt() (t time.Time, err error) {
return parseMailgunTime(i.CreatedAt)
}

// GetCode will return the bounce code for the message, regardless if it was
// returned as a string or as an integer. This method overcomes a protocol
// bug in the Mailgun API.
func (b Bounce) GetCode() (int, error) {
switch c := b.code.(type) {
case int:
return c, nil
case string:
return strconv.Atoi(c)
default:
return -1, strconv.ErrSyntax
}
}

// GetBounces returns a complete set of bounces logged against the sender's domain, if any.
// The results include the total number of bounces (regardless of skip or limit settings),
// and the slice of bounces specified, if successful.
Expand Down
43 changes: 43 additions & 0 deletions mailgun_test.go
@@ -1,6 +1,7 @@
package mailgun

import (
"strconv"
"testing"
)

Expand All @@ -23,3 +24,45 @@ func TestMailgun(t *testing.T) {
t.Fatal("PublicApiKey not equal!")
}
}

func TestBounceGetCode(t *testing.T) {
b1 := &Bounce{
CreatedAt: "blah",
code: 123,
Address: "blort",
Error: "bletch",
}
c, err := b1.GetCode()
if err != nil {
t.Fatal(err)
}
if c != 123 {
t.Fatal("Expected 123; got ", c)
}

b2 := &Bounce{
CreatedAt: "blah",
code: "456",
Address: "blort",
Error: "Bletch",
}
c, err = b2.GetCode()
if err != nil {
t.Fatal(err)
}
if c != 456 {
t.Fatal("Expected 456; got ", c)
}

b3 := &Bounce{
CreatedAt: "blah",
code: "456H",
Address: "blort",
Error: "Bletch",
}
c, err = b3.GetCode()
e, ok := err.(*strconv.NumError)
if !ok && e != nil {
t.Fatal("Expected a syntax error in numeric conversion: got ", err)
}
}

0 comments on commit e83dcc3

Please sign in to comment.