2021-11-30 18:15:21 +07:00
|
|
|
package configuration
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/mail"
|
|
|
|
"reflect"
|
|
|
|
|
|
|
|
"github.com/mitchellh/mapstructure"
|
|
|
|
)
|
|
|
|
|
|
|
|
// StringToMailAddressFunc decodes a string into a mail.Address.
|
|
|
|
func StringToMailAddressFunc() mapstructure.DecodeHookFunc {
|
2022-01-15 09:01:40 +07:00
|
|
|
return func(f reflect.Type, t reflect.Type, data interface{}) (value interface{}, err error) {
|
|
|
|
if f.Kind() != reflect.String || t != reflect.TypeOf(mail.Address{}) {
|
2021-11-30 18:15:21 +07:00
|
|
|
return data, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
dataStr := data.(string)
|
|
|
|
|
|
|
|
if dataStr == "" {
|
|
|
|
return mail.Address{}, nil
|
|
|
|
}
|
|
|
|
|
|
|
|
var (
|
|
|
|
mailAddress *mail.Address
|
|
|
|
)
|
|
|
|
|
|
|
|
mailAddress, err = mail.ParseAddress(dataStr)
|
|
|
|
if err != nil {
|
|
|
|
return nil, fmt.Errorf("could not parse '%s' as a RFC5322 address: %w", dataStr, err)
|
|
|
|
}
|
|
|
|
|
|
|
|
return *mailAddress, nil
|
|
|
|
}
|
|
|
|
}
|