密码重置功能:在 Golang 中发送电子邮件
一分耕耘,一分收获!既然都打开这篇《密码重置功能:在 Golang 中发送电子邮件》,就坚持看下去,学下去吧!本文主要会给大家讲到等等知识点,如果大家对本文有好的建议或者看到有不足之处,非常欢迎大家积极提出!在后续文章我会继续更新Golang相关的内容,希望对大家都有所帮助!

在撰写本文时,我正在我的应用程序 task-inator 3000 中实现一项为用户重置密码的功能。只是记录我的思考过程和采取的步骤
规划
我正在考虑这样的流程:
- 用户点击“忘记密码?”按钮
- 向请求电子邮件的用户显示模式
- 检查电子邮件是否存在,并将 10 个字符长的 otp 发送到电子邮件
- modal 现在要求输入 otp 和新密码
- 密码已为用户进行哈希处理和更新
关注点分离
前端
- 创建一个模态来输入电子邮件
- 相同的模式然后接受 otp 和新密码
后端
- 创建用于发送电子邮件的 api
- 创建重置密码的api
我将从后端开始
后端
如上所述,我们需要两个 api
1. 发送邮件
api只需要接收用户的邮件,成功后不返回任何内容。因此,创建控制器如下:
// controllers/passwordreset.go
func sendpasswordresetemail(c *fiber.ctx) error {
type input struct {
email string `json:"email"`
}
var input input
err := c.bodyparser(&input)
if err != nil {
return c.status(fiber.statusbadrequest).json(fiber.map{
"error": "invalid data",
})
}
// todo: send email with otp to user
return c.sendstatus(fiber.statusnocontent)
}
现在为其添加一条路线:
// routes/routes.go
// password reset
api.post("/send-otp", controllers.sendpasswordresetemail)
我将使用 golang 标准库中的 net/smtp。
阅读文档后,我认为最好在项目初始化时创建一个 smtpclient。因此,我会在 /config 目录中创建一个文件 smtpconnection.go。
在此之前,我会将以下环境变量添加到我的 .env 或生产服务器中。
smtp_host="smtp.zoho.in" smtp_port="587" smtp_email="<myemail>" smtp_password="<mypassword>"
我使用的是 zohomail,因此其 smtp 主机和端口(用于 tls)如此处所述。
// config/smtpconnection.go
package config
import (
"crypto/tls"
"fmt"
"net/smtp"
"os"
)
var smtpclient *smtp.client
func smtpconnect() {
host := os.getenv("smtp_host")
port := os.getenv("smtp_port")
email := os.getenv("smtp_email")
password := os.getenv("smtp_password")
smtpauth := smtp.plainauth("", email, password, host)
// connect to smtp server
client, err := smtp.dial(host + ":" + port)
if err != nil {
panic(err)
}
smtpclient = client
client = nil
// initiate tls handshake
if ok, _ := smtpclient.extension("starttls"); ok {
config := &tls.config{servername: host}
if err = smtpclient.starttls(config); err != nil {
panic(err)
}
}
// authenticate
err = smtpclient.auth(smtpauth)
if err != nil {
panic(err)
}
fmt.println("smtp connected")
}
为了抽象,我将在/utils 中创建一个passwordreset.go 文件。该文件目前具有以下功能:
- 生成 otp:生成一个唯一的字母数字 10 位 otp 以在电子邮件中发送
- addotptoredis:以键值格式将 otp 添加到 redis,其中
key -> password-reset:<email> value -> hashed otp expiry -> 10 mins
出于安全原因,我存储 otp 的哈希值而不是 otp 本身
- sendotp:将生成的 otp 发送到用户的电子邮件
在编写代码时,我发现我们需要 5 个常量:
- otp 的 redis 密钥前缀
- otp 过期时间
- 用于 otp 生成的字符集
- 电子邮件模板
- otp 长度
我会立即将它们添加到 /utils/constants.go
// utils/constants.go
package utils
import "time"
const (
authtokenexp = time.minute * 10
refreshtokenexp = time.hour * 24 * 30 // 1 month
blacklistkeyprefix = "blacklisted:"
otpkeyprefix = "password-reset:"
otpexp = time.minute * 10
otpcharset = "abcdefghijklmnopqrstuvwxyz1234567890"
emailtemplate = "to: %s\r\n" +
"subject: task-inator 3000 password reset\r\n" +
"\r\n" +
"your otp for password reset is %s\r\n"
// public because needed for testing
otplength = 10
)
(请注意,我们将从 crypto/rand 导入,而不是 math/rand,因为它将提供真正的随机性)
// utils/passwordreset.go
package utils
import (
"context"
"crypto/rand"
"fmt"
"math/big"
"os"
"task-inator3000/config"
"golang.org/x/crypto/bcrypt"
)
func generateotp() string {
result := make([]byte, otplength)
charsetlength := big.newint(int64(len(otpcharset)))
for i := range result {
// generate a secure random number in the range of the charset length
num, _ := rand.int(rand.reader, charsetlength)
result[i] = otpcharset[num.int64()]
}
return string(result)
}
func addotptoredis(otp string, email string, c context.context) error {
key := otpkeyprefix + email
// hashing the otp
data, _ := bcrypt.generatefrompassword([]byte(otp), 10)
// storing otp with expiry
err := config.redisclient.set(c, key, data, otpexp).err()
if err != nil {
return err
}
return nil
}
func sendotp(otp string, recipient string) error {
sender := os.getenv("smtp_email")
client := config.smtpclient
// setting the sender
err := client.mail(sender)
if err != nil {
return err
}
// set recipient
err = client.rcpt(recipient)
if err != nil {
return err
}
// start writing email
writecloser, err := client.data()
if err != nil {
return err
}
// contents of the email
msg := fmt.sprintf(emailtemplate, recipient, otp)
// write the email
_, err = writecloser.write([]byte(msg))
if err != nil {
return err
}
// close writecloser and send email
err = writecloser.close()
if err != nil {
return err
}
return nil
}
函数generateotp()无需模拟即可测试(单元测试),因此为它编写了一个简单的测试
package utils_test
import (
"task-inator3000/utils"
"testing"
)
func testgenerateotp(t *testing.t) {
result := utils.generateotp()
if len(result) != utils.otplength {
t.errorf("length of otp was not %v. otp: %v", utils.otplength, result)
}
}
现在我们需要将它们全部放在控制器内。在这之前,我们需要确保数据库中存在提供的电子邮件地址。
控制器的完整代码如下:
func sendpasswordresetemail(c *fiber.ctx) error {
type input struct {
email string `json:"email"`
}
var input input
err := c.bodyparser(&input)
if err != nil {
return c.status(fiber.statusbadrequest).json(fiber.map{
"error": "invalid data",
})
}
// check if user with email exists
users := config.db.collection("users")
filter := bson.m{"_id": input.email}
err = users.findone(c.context(), filter).err()
if err != nil {
if err == mongo.errnodocuments {
return c.status(fiber.statusnotfound).json(fiber.map{
"error": "user with given email not found",
})
}
return c.status(fiber.statusinternalservererror).json(fiber.map{
"error": "error while finding in the database:\n" + err.error(),
})
}
// generate otp and add it to redis
otp := utils.generateotp()
err = utils.addotptoredis(otp, input.email, c.context())
if err != nil {
return c.status(fiber.statusinternalservererror).json(fiber.map{
"error": err.error(),
})
}
// send the otp to user through email
err = utils.sendotp(otp, input.email)
if err != nil {
return c.status(fiber.statusinternalservererror).json(fiber.map{
"error": err.error(),
})
}
return c.sendstatus(fiber.statusnocontent)
}
我们可以通过向正确的 url 发送 post 请求来测试 api。 curl 示例如下:
curl --location 'localhost:3000/api/send-otp' \
--header 'Content-Type: application/json' \
--data-raw '{
"email": "yashjaiswal.cse@gmail.com"
}'
我们将在本系列的下一部分中创建下一个 api - 用于重置密码
终于介绍完啦!小伙伴们,这篇关于《密码重置功能:在 Golang 中发送电子邮件》的介绍应该让你收获多多了吧!欢迎大家收藏或分享给更多需要学习的朋友吧~golang学习网公众号也会发布Golang相关知识,快来关注吧!
用户快速重复提交表单,如何防止数据库插入重复数据?
- 上一篇
- 用户快速重复提交表单,如何防止数据库插入重复数据?
- 下一篇
- 儿童几岁可以练习书法?
-
- Golang · Go教程 | 1小时前 |
- Golangreflect动态赋值方法详解
- 299浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang标准库与依赖安装详解
- 350浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang微服务熔断降级实现详解
- 190浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Go语言指针操作:*的多义与隐式&
- 325浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang自动扩容策略怎么实现
- 145浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang指针与闭包关系详解
- 272浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang自定义错误详解与教程
- 110浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- GolangJSON读写实战教程详解
- 289浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- gorun支持从标准输入执行代码吗?
- 408浏览 收藏
-
- Golang · Go教程 | 1小时前 |
- Golang环境搭建与依赖安装指南
- 368浏览 收藏
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
-
- ChatExcel酷表
- ChatExcel酷表是由北京大学团队打造的Excel聊天机器人,用自然语言操控表格,简化数据处理,告别繁琐操作,提升工作效率!适用于学生、上班族及政府人员。
- 3190次使用
-
- Any绘本
- 探索Any绘本(anypicturebook.com/zh),一款开源免费的AI绘本创作工具,基于Google Gemini与Flux AI模型,让您轻松创作个性化绘本。适用于家庭、教育、创作等多种场景,零门槛,高自由度,技术透明,本地可控。
- 3402次使用
-
- 可赞AI
- 可赞AI,AI驱动的办公可视化智能工具,助您轻松实现文本与可视化元素高效转化。无论是智能文档生成、多格式文本解析,还是一键生成专业图表、脑图、知识卡片,可赞AI都能让信息处理更清晰高效。覆盖数据汇报、会议纪要、内容营销等全场景,大幅提升办公效率,降低专业门槛,是您提升工作效率的得力助手。
- 3433次使用
-
- 星月写作
- 星月写作是国内首款聚焦中文网络小说创作的AI辅助工具,解决网文作者从构思到变现的全流程痛点。AI扫榜、专属模板、全链路适配,助力新人快速上手,资深作者效率倍增。
- 4540次使用
-
- MagicLight
- MagicLight.ai是全球首款叙事驱动型AI动画视频创作平台,专注于解决从故事想法到完整动画的全流程痛点。它通过自研AI模型,保障角色、风格、场景高度一致性,让零动画经验者也能高效产出专业级叙事内容。广泛适用于独立创作者、动画工作室、教育机构及企业营销,助您轻松实现创意落地与商业化。
- 3811次使用
-
- Golangmap实践及实现原理解析
- 2022-12-28 505浏览
-
- go和golang的区别解析:帮你选择合适的编程语言
- 2023-12-29 503浏览
-
- 试了下Golang实现try catch的方法
- 2022-12-27 502浏览
-
- 如何在go语言中实现高并发的服务器架构
- 2023-08-27 502浏览
-
- 提升工作效率的Go语言项目开发经验分享
- 2023-11-03 502浏览

