2 回答
TA贡献1856条经验 获得超11个赞
首先,对于错误处理,err在返回之前检查是否为nil!
所以不是:
myEmail, err := LoadEnvVariable("EMAIL")
return "", err
但反而:
myEmail, err := LoadEnvVariable("EMAIL")
if err != nil {
return "", err
}
其次,单个字符串类型""与固定数组大小兼容[4]string。使用命名返回变量可能会让您的生活更轻松,因此您不需要在发生错误时传递显式的“零”值。所以像这样定义你的函数签名:
func Email(in [4]string) (out [4]string, err error) {
myEmail, err := LoadEnvVariable("EMAIL")
if err != nil {
return // implicitly returns 'out' and 'err'
}
// ...
out = in
return // implicitly returns 'out' and nil 'err'
}
TA贡献1770条经验 获得超3个赞
用它来检查错误
if err != nil {
return "", err
}
func LoadEnvVariable(key string) (string, error) {
viper.SetConfigFile(".env")
err := viper.ReadInConfig()
if err != nil {
return "", err
}
value, ok := viper.Get(key).(string)
if !ok {
return "", err
}
return value, nil
}
func Email(value [4]string) ([4]string, error) {
mail := gomail.NewMessage()
myEmail, err := LoadEnvVariable("EMAIL")
if err != nil {
return "", err
}
appPassword, err := LoadEnvVariable("APP_PASSWORD")
if err != nil {
return "", err
}
mail.SetHeader("From", myEmail)
mail.SetHeader("To", myEmail)
mail.SetHeader("Reply-To", value[1])
mail.SetHeader("subject", value[2])
mail.SetBody("text/plain", value[3])
a := gomail.NewDialer("smtp.gmail.com", 587, myEmail, appPassword)
err = a.DialAndSend(mail)
if err != nil {
return "", err
}
return value, nil
}
- 2 回答
- 0 关注
- 90 浏览
添加回答
举报