Skip to content

Commit

Permalink
Merge pull request #6 from gostalt/mx-email-validator
Browse files Browse the repository at this point in the history
enable a timeout to be passed to MXEmail validator
  • Loading branch information
tmus authored Oct 15, 2019
2 parents 242152f + 019ebb9 commit e5e326b
Show file tree
Hide file tree
Showing 2 changed files with 19 additions and 3 deletions.
13 changes: 11 additions & 2 deletions rule.go
Original file line number Diff line number Diff line change
@@ -1,6 +1,7 @@
package validate

import (
"context"
"fmt"
"net"
"net/http"
Expand Down Expand Up @@ -162,15 +163,23 @@ var NotRegex CheckFunc = func(r *http.Request, param string, o Options) error {
// MXEmail looks up the MX Records on a domain to check if a record exists. If
// an MX record exists, it is likely that the email address is real. This is
// smarter than just checking if an email address fits a certain format.
var MXEmail CheckFunc = func(r *http.Request, param string, _ Options) error {
var MXEmail CheckFunc = func(r *http.Request, param string, o Options) error {
if err := Email(r, param, nil); err != nil {
return err
}

timeout, ok := o["timeout"].(int)
if !ok {
timeout = 5
}

parts := strings.Split(r.Form.Get(param), "@")
domain := parts[len(parts)-1]

records, err := net.LookupMX(domain)
rsv := net.Resolver{}
ctx, cancel := context.WithTimeout(r.Context(), time.Duration(timeout)*time.Second)
defer cancel()
records, err := rsv.LookupMX(ctx, domain)
if err != nil {
return fmt.Errorf("failed to look up MX records for %s", param)
}
Expand Down
9 changes: 8 additions & 1 deletion rule_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -75,7 +75,14 @@ func TestRules(t *testing.T) {
MXEmail,
[]string{"[email protected]", "[email protected]"},
[]string{"me@[email protected]", "juststring", "me@[email protected]"},
nil,
Options{"timeout": 10},
},
{
// MXEmail, but with a short timeout.
MXEmail,
[]string{}, // No `passable` values, as these should all time out.
[]string{"me@[email protected]", "juststring", "me@[email protected]"},
Options{"timeout": 1},
},
{
RFC3339,
Expand Down

0 comments on commit e5e326b

Please sign in to comment.