text
stringlengths 76
10.6k
|
---|
// StoreLog is used to store a single raft log
func (b *BoltStore) StoreLog(log *raft.Log) error {
return b.StoreLogs([]*raft.Log{log})
} |
// StoreLogs is used to store a set of raft logs
func (b *BoltStore) StoreLogs(logs []*raft.Log) error {
tx, err := b.conn.Begin(true)
if err!= nil {
return err
}
defer tx.Rollback()
for _, log := range logs {
key := uint64ToBytes(log.Index)
val, err := encodeMsgPack(log)
if err!= nil {
return err
}
bucket := tx.Bucket(dbLogs)
if err := bucket.Put(key, val.Bytes()); err!= nil {
return err
}
}
return tx.Commit()
} |
// DeleteRange is used to delete logs within a given range inclusively.
func (b *BoltStore) DeleteRange(min, max uint64) error {
minKey := uint64ToBytes(min)
tx, err := b.conn.Begin(true)
if err!= nil {
return err
}
defer tx.Rollback()
curs := tx.Bucket(dbLogs).Cursor()
for k, _ := curs.Seek(minKey); k!= nil; k, _ = curs.Next() {
// Handle out-of-range log index
if bytesToUint64(k) > max {
break
}
// Delete in-range log index
if err := curs.Delete(); err!= nil {
return err
}
}
return tx.Commit()
} |
// Set is used to set a key/value set outside of the raft log
func (b *BoltStore) Set(k, v []byte) error {
tx, err := b.conn.Begin(true)
if err!= nil {
return err
}
defer tx.Rollback()
bucket := tx.Bucket(dbConf)
if err := bucket.Put(k, v); err!= nil {
return err
}
return tx.Commit()
} |
// Get is used to retrieve a value from the k/v store by key
func (b *BoltStore) Get(k []byte) ([]byte, error) {
tx, err := b.conn.Begin(false)
if err!= nil {
return nil, err
}
defer tx.Rollback()
bucket := tx.Bucket(dbConf)
val := bucket.Get(k)
if val == nil {
return nil, ErrKeyNotFound
}
return append([]byte(nil), val...), nil
} |
// SetUint64 is like Set, but handles uint64 values
func (b *BoltStore) SetUint64(key []byte, val uint64) error {
return b.Set(key, uint64ToBytes(val))
} |
// GetUint64 is like Get, but handles uint64 values
func (b *BoltStore) GetUint64(key []byte) (uint64, error) {
val, err := b.Get(key)
if err!= nil {
return 0, err
}
return bytesToUint64(val), nil
} |
// ListDomains retrieves a set of domains from Mailgun.
func (mg *MailgunImpl) ListDomains(opts *ListOptions) *DomainsIterator {
var limit int
if opts!= nil {
limit = opts.Limit
}
if limit == 0 {
limit = 100
}
return &DomainsIterator{
mg: mg,
url: generatePublicApiUrl(mg, domainsEndpoint),
domainsListResponse: domainsListResponse{TotalCount: -1},
limit: limit,
}
} |
// Next retrieves the next page of items from the api. Returns false when there
// no more pages to retrieve or if there was an error. Use `.Err()` to retrieve
// the error
func (ri *DomainsIterator) Next(ctx context.Context, items *[]Domain) bool {
if ri.err!= nil {
return false
}
ri.err = ri.fetch(ctx, ri.offset, ri.limit)
if ri.err!= nil {
return false
}
cpy := make([]Domain, len(ri.Items))
copy(cpy, ri.Items)
*items = cpy
if len(ri.Items) == 0 {
return false
}
ri.offset = ri.offset + len(ri.Items)
return true
} |
// GetDomain retrieves detailed information about the named domain.
func (mg *MailgunImpl) GetDomain(ctx context.Context, domain string) (DomainResponse, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var resp DomainResponse
err := getResponseFromJSON(ctx, r, &resp)
return resp, err
} |
// CreateDomain instructs Mailgun to create a new domain for your account.
// The name parameter identifies the domain.
// The smtpPassword parameter provides an access credential for the domain.
// The spamAction domain must be one of Delete, Tag, or Disabled.
// The wildcard parameter instructs Mailgun to treat all subdomains of this domain uniformly if true,
// and as different domains if false.
func (mg *MailgunImpl) CreateDomain(ctx context.Context, name string, opts *CreateDomainOptions) (DomainResponse, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint))
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
payload := newUrlEncodedPayload()
payload.addValue("name", name)
if opts!= nil {
if opts.SpamAction!= "" {
payload.addValue("spam_action", string(opts.SpamAction))
}
if opts.Wildcard {
payload.addValue("wildcard", boolToString(opts.Wildcard))
}
if opts.ForceDKIMAuthority {
payload.addValue("force_dkim_authority", boolToString(opts.ForceDKIMAuthority))
}
if opts.DKIMKeySize!= 0 {
payload.addValue("dkim_key_size", strconv.Itoa(opts.DKIMKeySize))
}
if len(opts.IPS)!= 0 {
payload.addValue("ips", strings.Join(opts.IPS, ","))
}
if len(opts.Password)!= 0 {
payload.addValue("smtp_password", opts.Password)
}
}
var resp DomainResponse
err := postResponseFromJSON(ctx, r, payload, &resp)
return resp, err
} |
// GetDomainConnection returns delivery connection settings for the defined domain
func (mg *MailgunImpl) GetDomainConnection(ctx context.Context, 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(ctx, r, &resp)
return resp.Connection, err
} |
// Updates the specified delivery connection settings for the defined domain
func (mg *MailgunImpl) UpdateDomainConnection(ctx context.Context, 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(ctx, r, payload)
return err
} |
// DeleteDomain instructs Mailgun to dispose of the named domain name
func (mg *MailgunImpl) DeleteDomain(ctx context.Context, name string) error {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + name)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
_, err := makeDeleteRequest(ctx, r)
return err
} |
// GetDomainTracking returns tracking settings for a domain
func (mg *MailgunImpl) GetDomainTracking(ctx context.Context, domain string) (DomainTracking, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, domainsEndpoint) + "/" + domain + "/tracking")
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var resp domainTrackingResponse
err := getResponseFromJSON(ctx, r, &resp)
return resp.Tracking, err
} |
// Creates a new validation instance.
// * If a public key is provided, uses the public validation endpoints
// * If a private key is provided, uses the private validation endpoints
func NewEmailValidator(apiKey string) *EmailValidatorImpl {
isPublicKey := false
// Did the user pass in a public key?
if strings.HasPrefix(apiKey, "pubkey-") {
isPublicKey = true
}
return &EmailValidatorImpl{
client: http.DefaultClient,
isPublicKey: isPublicKey,
apiBase: APIBase,
apiKey: apiKey,
}
} |
// NewEmailValidatorFromEnv returns a new EmailValidator using environment variables
// If MG_PUBLIC_API_KEY is set, assume using the free validation subject to daily usage limits
// If only MG_API_KEY is set, assume using the /private validation routes with no daily usage limits
func NewEmailValidatorFromEnv() (*EmailValidatorImpl, error) {
apiKey := os.Getenv("MG_PUBLIC_API_KEY")
if apiKey == "" {
apiKey = os.Getenv("MG_API_KEY")
if apiKey == "" {
return nil, errors.New(
"environment variable MG_PUBLIC_API_KEY or MG_API_KEY required for email validation")
}
}
v := NewEmailValidator(apiKey)
url := os.Getenv("MG_URL")
if url!= "" {
v.SetAPIBase(url)
}
return v, nil
} |
// ValidateEmail performs various checks on the email address provided to ensure it's correctly formatted.
// It may also be used to break an email address into its sub-components. (See example.)
func (m *EmailValidatorImpl) ValidateEmail(ctx context.Context, email string, mailBoxVerify bool) (EmailVerification, error) {
r := newHTTPRequest(m.getAddressURL("validate"))
r.setClient(m.Client())
r.addParameter("address", email)
if mailBoxVerify {
r.addParameter("mailbox_verification", "true")
}
r.setBasicAuth(basicAuthUser, m.APIKey())
var response EmailVerification
err := getResponseFromJSON(ctx, r, &response)
if err!= nil {
return EmailVerification{}, err
}
return response, nil
} |
// ParseAddresses takes a list of addresses and sorts them into valid and invalid address categories.
// NOTE: Use of this function requires a proper public API key. The private API key will not work.
func (m *EmailValidatorImpl) ParseAddresses(ctx context.Context, addresses...string) ([]string, []string, error) {
r := newHTTPRequest(m.getAddressURL("parse"))
r.setClient(m.Client())
r.addParameter("addresses", strings.Join(addresses, ","))
r.setBasicAuth(basicAuthUser, m.APIKey())
var response addressParseResult
err := getResponseFromJSON(ctx, r, &response)
if err!= nil {
return nil, nil, err
}
return response.Parsed, response.Unparseable, nil
} |
// ListWebhooks returns the complete set of webhooks configured for your domain.
// Note that a zero-length mapping is not an error.
func (mg *MailgunImpl) ListWebhooks(ctx context.Context) (map[string]string, error) {
r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint))
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var envelope struct {
Webhooks map[string]interface{} `json:"webhooks"`
}
err := getResponseFromJSON(ctx, r, &envelope)
hooks := make(map[string]string, 0)
if err!= nil {
return hooks, err
}
for k, v := range envelope.Webhooks {
object := v.(map[string]interface{})
url := object["url"]
hooks[k] = url.(string)
}
return hooks, nil
} |
// DeleteWebhook removes the specified webhook from your domain's configuration.
func (mg *MailgunImpl) DeleteWebhook(ctx context.Context, t string) error {
r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
_, err := makeDeleteRequest(ctx, r)
return err
} |
// GetWebhook retrieves the currently assigned webhook URL associated with the provided type of webhook.
func (mg *MailgunImpl) GetWebhook(ctx context.Context, t string) (string, error) {
r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
var envelope struct {
Webhook struct {
Url string `json:"url"`
} `json:"webhook"`
}
err := getResponseFromJSON(ctx, r, &envelope)
return envelope.Webhook.Url, err
} |
// UpdateWebhook replaces one webhook setting for another.
func (mg *MailgunImpl) UpdateWebhook(ctx context.Context, t string, urls []string) error {
r := newHTTPRequest(generateDomainApiUrl(mg, webhooksEndpoint) + "/" + t)
r.setClient(mg.Client())
r.setBasicAuth(basicAuthUser, mg.APIKey())
p := newUrlEncodedPayload()
for _, url := range urls {
p.addValue("url", url)
}
_, err := makePutRequest(ctx, r, p)
return err
} |
// Use this method to parse the webhook signature given as JSON in the webhook response
func (mg *MailgunImpl) VerifyWebhookSignature(sig Signature) (verified bool, err error) {
h := hmac.New(sha256.New, []byte(mg.APIKey()))
io.WriteString(h, sig.TimeStamp)
io.WriteString(h, sig.Token)
calculatedSignature := h.Sum(nil)
signature, err := hex.DecodeString(sig.Signature)
if err!= nil {
return false, err
}
if len(calculatedSignature)!= len(signature) {
return false, nil
}
return subtle.ConstantTimeCompare(signature, calculatedSignature) == 1, nil
} |
// Deprecated: Please use the VerifyWebhookSignature() to parse the latest
// version of WebHooks from mailgun
func (mg *MailgunImpl) VerifyWebhookRequest(req *http.Request) (verified bool, err error) {
h := hmac.New(sha256.New, []byte(mg.APIKey()))
io.WriteString(h, req.FormValue("timestamp"))
io.WriteString(h, req.FormValue("token"))
calculatedSignature := h.Sum(nil)
signature, err := hex.DecodeString(req.FormValue("signature"))
if err!= nil {
return false, err
}
if len(calculatedSignature)!= len(signature) {
return false, nil
}
return subtle.ConstantTimeCompare(signature, calculatedSignature) == 1, nil
} |
// String() converts the error into a human-readable, logfmt-compliant string.
// See http://godoc.org/github.com/kr/logfmt for details on logfmt formatting.
func (e *UnexpectedResponseError) String() string {
return fmt.Sprintf("UnexpectedResponseError URL=%s ExpectedOneOf=%#v Got=%d Error: %s", e.URL, e.Expected, e.Actual, string(e.Data))
} |
// newError creates a new error condition to be returned.
func newError(url string, expected []int, got *httpResponse) error {
return &UnexpectedResponseError{
URL: url,
Expected: expected,
Actual: got.Code,
Data: got.Data,
}
} |
// makeRequest shim performs a generic request, checking for a positive outcome.
// See simplehttp.MakeRequest for more details.
func makeRequest(ctx context.Context, r *httpRequest, method string, p payload) (*httpResponse, error) {
r.addHeader("User-Agent", MailgunGoUserAgent)
rsp, err := r.makeRequest(ctx, method, p)
if (err == nil) && notGood(rsp.Code, expected) {
return rsp, newError(r.URL, expected, rsp)
}
return rsp, err
} |
// getResponseFromJSON shim performs a GET request, checking for a positive outcome.
// See simplehttp.GetResponseFromJSON for more details.
func getResponseFromJSON(ctx context.Context, r *httpRequest, v interface{}) error {
r.addHeader("User-Agent", MailgunGoUserAgent)
response, err := r.makeGetRequest(ctx)
if err!= nil {
return err
}
if notGood(response.Code, expected) {
return newError(r.URL, expected, response)
}
return response.parseFromJSON(v)
} |
// postResponseFromJSON shim performs a POST request, checking for a positive outcome.
// See simplehttp.PostResponseFromJSON for more details.
func postResponseFromJSON(ctx context.Context, r *httpRequest, p payload, v interface{}) error {
r.addHeader("User-Agent", MailgunGoUserAgent)
response, err := r.makePostRequest(ctx, p)
if err!= nil {
return err
}
if notGood(response.Code, expected) {
return newError(r.URL, expected, response)
}
return response.parseFromJSON(v)
} |
// Extract the http status code from error object
func GetStatusFromErr(err error) int {
obj, ok := err.(*UnexpectedResponseError)
if!ok {
return -1
}
return obj.Actual
} |
// ListIPS returns a list of IPs assigned to your account
func (mg *MailgunImpl) ListIPS(ctx context.Context, dedicated bool) ([]IPAddress, error) {
r := newHTTPRequest(generatePublicApiUrl(mg, ipsEndpoint))
r.setClient(mg.Client())
if dedicated {
r.addParameter("dedicated", "true")
}
r.setBasicAuth(basicAuthUser, mg.APIKey())
var resp ipAddressListResponse
if err := getResponseFromJSON(ctx, r, &resp); err!= nil {
return nil, err
}
var result []IPAddress
for _, ip := range resp.Items {
result = append(result, IPAddress{IP: ip})
}
return result, nil
} |