Skip to content

Commit

Permalink
Added support for domain connection
Browse files Browse the repository at this point in the history
  • Loading branch information
thrawn01 committed Jan 4, 2019
1 parent b4d5e60 commit e57a28e
Show file tree
Hide file tree
Showing 16 changed files with 461 additions and 188 deletions.
47 changes: 47 additions & 0 deletions cmd/mailgun/events.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,47 @@
package main

import (
"github.com/davecgh/go-spew/spew"

"github.com/mailgun/mailgun-go"
"github.com/thrawn01/args"
)

func ListEvents(parser *args.ArgParser, data interface{}) (int, error) {
mg := data.(mailgun.Mailgun)

desc := args.Dedent(`list events via the mailgun HTTP API
Examples:
list all available tags
$ mailgun events
limit each event page to 100 events
$ mailgun events -l 100`)

parser.SetDesc(desc)
parser.AddOption("--limit").Alias("-l").IsInt().Help("Limit the page size")

opts := parser.ParseSimple(nil)
if opts == nil {
return 1, nil
}

limit := opts.Int("limit")

// Create the event iterator
it := mg.ListEvents(&mailgun.EventsOptions{
Limit: limit,
})

var page []mailgun.Event
for it.Next(&page) {
for _, event := range page {
spew.Printf("%+v\n", event)
}
}
if it.Err() != nil {
return 1, it.Err()
}
return 0, nil
}
1 change: 1 addition & 0 deletions cmd/mailgun/main.go
Original file line number Diff line number Diff line change
Expand Up @@ -34,6 +34,7 @@ func main() {
// Commands
parser.AddCommand("send", Send)
parser.AddCommand("tag", Tag)
parser.AddCommand("events", ListEvents)

// Parser and set global options
opts := parser.ParseOrExit(nil)
Expand Down
2 changes: 1 addition & 1 deletion cmd/mailgun/tag.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@ import (
"encoding/json"
"fmt"

mailgun "github.com/mailgun/mailgun-go"
"github.com/mailgun/mailgun-go"
"github.com/thrawn01/args"
)

Expand Down
57 changes: 48 additions & 9 deletions domains.go
Original file line number Diff line number Diff line change
Expand Up @@ -30,6 +30,7 @@ type Domain struct {
SMTPPassword string `json:"smtp_password"`
Wildcard bool `json:"wildcard"`
SpamAction string `json:"spam_action"`
State string `json:"state"`
}

// DNSRecord structures describe intended records to properly configure your domain for use with Mailgun.
Expand All @@ -42,15 +43,25 @@ type DNSRecord struct {
Value string
}

type domainsEnvelope struct {
type SingleDomainResponse struct {
Domain Domain `json:"domain"`
ReceivingDNSRecords []DNSRecord `json:"receiving_dns_records"`
SendingDNSRecords []DNSRecord `json:"sending_dns_records"`
Connection *DomainConnection `json:"connection,omitempty"`
}

type DomainConnectionResponse struct {
Connection DomainConnection `json:"connection"`
}

type DomainList struct {
TotalCount int `json:"total_count"`
Items []Domain `json:"items"`
}

type singleDomainEnvelope struct {
Domain Domain `json:"domain"`
ReceivingDNSRecords []DNSRecord `json:"receiving_dns_records"`
SendingDNSRecords []DNSRecord `json:"sending_dns_records"`
type DomainConnection struct {
RequireTLS bool `json:"require_tls"`
SkipVerification bool `json:"skip_verification"`
}

// GetCreatedAt returns the time the domain was created as a normal Go time.Time type.
Expand All @@ -76,20 +87,20 @@ func (mg *MailgunImpl) GetDomains(limit, skip int) (int, []Domain, error) {
}
r.setBasicAuth(basicAuthUser, mg.APIKey())

var envelope domainsEnvelope
err := getResponseFromJSON(r, &envelope)
var list DomainList
err := getResponseFromJSON(r, &list)
if err != nil {
return -1, nil, err
}
return envelope.TotalCount, envelope.Items, nil
return list.TotalCount, list.Items, nil
}

// Retrieve detailed information about the named domain.
func (mg *MailgunImpl) GetSingleDomain(domain string) (Domain, []DNSRecord, []DNSRecord, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var envelope singleDomainEnvelope
var envelope SingleDomainResponse
err := getResponseFromJSON(r, &envelope)
return envelope.Domain, envelope.ReceivingDNSRecords, envelope.SendingDNSRecords, err
}
Expand All @@ -114,6 +125,27 @@ func (mg *MailgunImpl) CreateDomain(name string, smtpPassword string, spamAction
return err
}

func (mg *MailgunImpl) GetDomainConnection(domain string) (DomainConnection, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/connection")
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var resp DomainConnectionResponse
err := getResponseFromJSON(r, &resp)
return resp.Connection, err
}

func (mg *MailgunImpl) UpdateDomainConnection(domain string, settings DomainConnection) error {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/connection")
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())

payload := newUrlEncodedPayload()
payload.addValue("require_tls", boolToString(settings.RequireTLS))
payload.addValue("skip_verification", boolToString(settings.SkipVerification))
_, err := makePutRequest(r, payload)
return err
}

// DeleteDomain instructs Mailgun to dispose of the named domain name.
func (mg *MailgunImpl) DeleteDomain(name string) error {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + name)
Expand All @@ -122,3 +154,10 @@ func (mg *MailgunImpl) DeleteDomain(name string) error {
_, err := makeDeleteRequest(r)
return err
}

func boolToString(b bool) string {
if b {
return "true"
}
return "false"
}
53 changes: 40 additions & 13 deletions domains_test.go
Original file line number Diff line number Diff line change
@@ -1,18 +1,21 @@
package mailgun
package mailgun_test

import (
"net/http"
"testing"

"github.com/facebookgo/ensure"
"github.com/mailgun/mailgun-go"
)

func TestGetDomains(t *testing.T) {
mg, err := NewMailgunFromEnv()
mg, err := mailgun.NewMailgunFromEnv()
mg.SetAPIBase(server.URL())
ensure.Nil(t, err)

n, domains, err := mg.GetDomains(DefaultLimit, DefaultSkip)
n, domains, err := mg.GetDomains(mailgun.DefaultLimit, mailgun.DefaultSkip)
ensure.Nil(t, err)
ensure.DeepEqual(t, len(domains) != 0, true)

t.Logf("TestGetDomains: %d domains retrieved\n", n)
for _, d := range domains {
Expand All @@ -21,14 +24,17 @@ func TestGetDomains(t *testing.T) {
}

func TestGetSingleDomain(t *testing.T) {
mg, err := NewMailgunFromEnv()
mg, err := mailgun.NewMailgunFromEnv()
mg.SetAPIBase(server.URL())
ensure.Nil(t, err)

_, domains, err := mg.GetDomains(DefaultLimit, DefaultSkip)
_, domains, err := mg.GetDomains(mailgun.DefaultLimit, mailgun.DefaultSkip)
ensure.Nil(t, err)

dr, rxDnsRecords, txDnsRecords, err := mg.GetSingleDomain(domains[0].Name)
ensure.Nil(t, err)
ensure.DeepEqual(t, len(rxDnsRecords) != 0, true)
ensure.DeepEqual(t, len(txDnsRecords) != 0, true)

t.Logf("TestGetSingleDomain: %#v\n", dr)
for _, rxd := range rxDnsRecords {
Expand All @@ -40,25 +46,46 @@ func TestGetSingleDomain(t *testing.T) {
}

func TestGetSingleDomainNotExist(t *testing.T) {
mg, err := NewMailgunFromEnv()
mg, err := mailgun.NewMailgunFromEnv()
mg.SetAPIBase(server.URL())
ensure.Nil(t, err)
_, _, _, err = mg.GetSingleDomain(randomString(32, "com.edu.org.") + ".com")
_, _, _, err = mg.GetSingleDomain("mailgun.test")
if err == nil {
t.Fatal("Did not expect a domain to exist")
}
ure, ok := err.(*UnexpectedResponseError)
ure, ok := err.(*mailgun.UnexpectedResponseError)
ensure.True(t, ok)
ensure.DeepEqual(t, ure.Actual, http.StatusNotFound)
}

func TestAddDeleteDomain(t *testing.T) {
mg, err := NewMailgunFromEnv()
mg, err := mailgun.NewMailgunFromEnv()
mg.SetAPIBase(server.URL())
ensure.Nil(t, err)

// First, we need to add the domain.
randomDomainName := randomString(16, "DOMAIN") + ".example.com"
randomPassword := randomString(16, "PASSWD")
ensure.Nil(t, mg.CreateDomain(randomDomainName, randomPassword, Tag, false))
ensure.Nil(t, mg.CreateDomain("mailgun.test", "supersecret", mailgun.Tag, false))
// Next, we delete it.
ensure.Nil(t, mg.DeleteDomain(randomDomainName))
ensure.Nil(t, mg.DeleteDomain("mailgun.test"))
}

func TestDomainConnection(t *testing.T) {
mg, err := mailgun.NewMailgunFromEnv()
mg.SetAPIBase(server.URL())
ensure.Nil(t, err)

info, err := mg.GetDomainConnection("samples.mailgun.org")
ensure.Nil(t, err)

ensure.DeepEqual(t, info.RequireTLS, true)
ensure.DeepEqual(t, info.SkipVerification, true)

info.RequireTLS = false
err = mg.UpdateDomainConnection("samples.mailgun.org", info)
ensure.Nil(t, err)

info, err = mg.GetDomainConnection("samples.mailgun.org")
ensure.Nil(t, err)
ensure.DeepEqual(t, info.RequireTLS, false)
ensure.DeepEqual(t, info.SkipVerification, true)
}
14 changes: 10 additions & 4 deletions exports.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,11 +4,17 @@ import (
"errors"
"fmt"
"net/http"

"github.com/mailgun/mailgun-go/schema"
)

type Export schema.Export
type ExportList struct {
Items []Export `json:"items"`
}

type Export struct {
ID string `json:"id"`
Status string `json:"status"`
URL string `json:"url"`
}

// Create an export based on the URL given
func (mg *MailgunImpl) CreateExport(url string) error {
Expand All @@ -31,7 +37,7 @@ func (mg *MailgunImpl) ListExports(url string) ([]Export, error) {
}
r.setBasicAuth(basicAuthUser, mg.APIKey())

var resp schema.ExportList
var resp ExportList
if err := getResponseFromJSON(r, &resp); err != nil {
return nil, err
}
Expand Down
19 changes: 15 additions & 4 deletions ips.go
Original file line number Diff line number Diff line change
@@ -1,8 +1,19 @@
package mailgun

import "github.com/mailgun/mailgun-go/schema"
type IPAddressList struct {
TotalCount int `json:"total_count"`
Items []string `json:"items"`
}

type IPAddress struct {
IP string `json:"ip"`
RDNS string `json:"rdns"`
Dedicated bool `json:"dedicated"`
}

type IPAddress schema.IPAddress
type OK struct {
Message string `json:"message"`
}

// Returns a list of IPs assigned to your account
func (mg *MailgunImpl) ListIPS(dedicated bool) ([]IPAddress, error) {
Expand All @@ -13,7 +24,7 @@ func (mg *MailgunImpl) ListIPS(dedicated bool) ([]IPAddress, error) {
}
r.setBasicAuth(basicAuthUser, mg.APIKey())

var resp schema.IPAddressList
var resp IPAddressList
if err := getResponseFromJSON(r, &resp); err != nil {
return nil, err
}
Expand All @@ -40,7 +51,7 @@ func (mg *MailgunImpl) ListDomainIPS() ([]IPAddress, error) {
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())

var resp schema.IPAddressList
var resp IPAddressList
if err := getResponseFromJSON(r, &resp); err != nil {
return nil, err
}
Expand Down
5 changes: 2 additions & 3 deletions ips_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -6,14 +6,13 @@ import (

"github.com/facebookgo/ensure"
"github.com/mailgun/mailgun-go"
"github.com/mailgun/mailgun-go/mock"
)

var server mock.MailgunServer
var server mailgun.MockServer

// Setup and shutdown the mailgun mock server for the entire test suite
func TestMain(m *testing.M) {
server = mock.NewServer()
server = mailgun.NewMockServer()
defer server.Stop()
os.Exit(m.Run())
}
Expand Down
2 changes: 2 additions & 0 deletions mailgun.go
Original file line number Diff line number Diff line change
Expand Up @@ -212,6 +212,8 @@ type Mailgun interface {
ListExports(url string) ([]Export, error)
GetExport(id string) (Export, error)
GetExportLink(id string) (string, error)
UpdateDomainConnection(domain string, settings DomainConnection) error
GetDomainConnection(domain string) (DomainConnection, error)
}

// MailgunImpl bundles data needed by a large number of methods in order to interact with the Mailgun API.
Expand Down
Loading

0 comments on commit e57a28e

Please sign in to comment.