Golang用户注册登录实现教程
2026-05-09 14:38:56
0浏览
收藏
本文手把手教你用Golang原生标准库从零实现安全、可运行的用户注册与登录系统——不依赖任何Web框架,涵盖SQLite数据库建模、bcrypt密码哈希加密、基于Cookie的Session会话管理及完整路由与模板渲染,代码结构清晰、注释详尽,既适合初学者理解Web认证核心原理,也明确指出了内存Session和HTTP传输等学习版局限,并给出Redis+HTTPS等生产级加固建议,是迈向Golang后端工程实践的扎实第一步。

用户注册与登录是大多数Web服务的基础功能。使用Golang实现这一功能并不复杂,关键在于合理设计路由、处理表单数据、安全存储密码以及管理会话。下面通过一个简单的实战项目,展示如何用原生Golang(不依赖框架)完成基础的用户注册与登录。
1. 项目结构与初始化
创建项目目录,例如 user-auth,结构如下:
├── main.go├── handlers/
│ ├── auth.go
├── models/
│ ├── user.go
├── templates/
│ ├── register.html
│ ├── login.html
│ └── profile.html
└── db/ └── db.go
使用Go Modules初始化:
go mod init user-auth2. 数据库与用户模型设计
使用SQLite作为轻量数据库存储用户信息。在 db/db.go 中初始化数据库连接:
package db import ( "database/sql" _ "github.com/mattn/go-sqlite3" ) var DB *sql.DB func InitDB() (*sql.DB, error) { db, err := sql.Open("sqlite3", "./users.db") if err != nil { return nil, err } DB = db createTable() return db, nil } func createTable() { query := `CREATE TABLE IF NOT EXISTS users ( id INTEGER PRIMARY KEY AUTOINCREMENT, username TEXT UNIQUE NOT NULL, password TEXT NOT NULL )` DB.Exec(query) }在 models/user.go 定义用户结构体:
package models type User struct { ID int Username string Password string }3. 密码安全:哈希存储
永远不要明文存储密码。使用Go标准库中的 golang.org/x/crypto/bcrypt 进行哈希处理。
安装bcrypt:
go get golang.org/x/crypto/bcrypt在注册时对密码进行哈希:
import "golang.org/x/crypto/bcrypt" func HashPassword(password string) (string, error) { bytes, err := bcrypt.GenerateFromPassword([]byte(password), 14) return string(bytes), err } func CheckPasswordHash(password, hash string) bool { err := bcrypt.CompareHashAndPassword([]byte(hash), []byte(password)) return err == nil }4. 注册功能实现
在 handlers/auth.go 中编写注册逻辑:
package handlers import ( "net/http" "html/template" "user-auth/models" "user-auth/db" ) func Register(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { tmpl := template.Must(template.ParseFiles("templates/register.html")) tmpl.Execute(w, nil) return } username := r.FormValue("username") password := r.FormValue("password") hashedPassword, _ := HashPassword(password) stmt, err := db.DB.Prepare("INSERT INTO users(username, password) VALUES(?, ?)") if err != nil { http.Error(w, "注册失败", 500) return } defer stmt.Close() _, err = stmt.Exec(username, hashedPassword) if err != nil { http.Error(w, "用户名已存在", 400) return } http.Redirect(w, r, "/login", http.StatusSeeOther) }5. 登录与Session管理
使用Cookie实现简单Session。登录成功后设置一个session token。
var sessions = make(map[string]string) // 简单内存存储,生产环境应使用Redis等 func Login(w http.ResponseWriter, r *http.Request) { if r.Method == "GET" { tmpl := template.Must(template.ParseFiles("templates/login.html")) tmpl.Execute(w, nil) return } username := r.FormValue("username") password := r.FormValue("password") var user models.User err := db.DB.QueryRow("SELECT username, password FROM users WHERE username = ?", username). Scan(&user.Username, &user.Password) if err != nil || !CheckPasswordHash(password, user.Password) { http.Error(w, "用户名或密码错误", 401) return } // 创建Session sessionID := generateSessionID() // 可用uuid或简单随机字符串 sessions[sessionID] = username http.SetCookie(w, &http.Cookie{ Name: "session_id", Value: sessionID, Path: "/", }) http.Redirect(w, r, "/profile", http.StatusSeeOther) }6. 用户个人页面与身份验证
保护需要登录才能访问的页面,例如用户个人页:
func Profile(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("session_id") if err != nil || sessions[cookie.Value] == "" { http.Redirect(w, r, "/login", http.StatusSeeOther) return } username := sessions[cookie.Value] tmpl := template.Must(template.ParseFiles("templates/profile.html")) tmpl.Execute(w, username) }templates/profile.html 示例:
欢迎,{{.}}!
退出7. 退出登录
清除Session和Cookie:
func Logout(w http.ResponseWriter, r *http.Request) { cookie, err := r.Cookie("session_id") if err == nil { delete(sessions, cookie.Value) } http.SetCookie(w, &http.Cookie{ Name: "session_id", Value: "", Path: "/", MaxAge: -1, }) http.Redirect(w, r, "/login", http.StatusSeeOther) }8. 路由注册(main.go)
package main import ( "net/http" "user-auth/handlers" "user-auth/db" ) func main() { db.InitDB() defer db.DB.Close() http.HandleFunc("/register", handlers.Register) http.HandleFunc("/login", handlers.Login) http.HandleFunc("/profile", handlers.Profile) http.HandleFunc("/logout", handlers.Logout) http.ListenAndServe(":8080", nil) }运行项目:go run main.go,访问 http://localhost:8080/register 开始测试。
基本上就这些。这个小项目涵盖了注册、登录、密码哈希、Session管理等核心要点。虽然用了内存存储Session,适合学习,实际生产建议结合Redis和HTTPS来提升安全性。
今天关于《Golang用户注册登录实现教程》的内容就介绍到这里了,是不是学起来一目了然!想要了解更多关于的内容请关注golang学习网公众号!
关闭Win10自动更新,软媒魔方实用教程
- 上一篇
- 关闭Win10自动更新,软媒魔方实用教程
- 下一篇
- Tailwindaspect-ratio实用教程详解
查看更多
最新文章
-
- Golang · Go教程 | 6小时前 | 配置管理 · 性能优化 · 并发编程 · Go教程 · 类型约束 RWMutex 配置快照 atomic.Pointer Go atomic.Value
- Go atomic.Value 存储配置快照的类型约束
- 485浏览 收藏
-
- Golang · Go教程 | 6小时前 |
- Go sync/atomic Uint64 对齐与无锁计数方案
- 165浏览 收藏
-
- Golang · Go教程 | 6小时前 | 性能优化 · 并发编程 · sync.Pool · 内存管理 · Go教程 · 垃圾回收 对象池 bytes.Buffer 临时对象 Go sync.Pool
- Go sync.Pool 缓存临时对象的回收边界
- 393浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- Go sync.Cond 生产者消费者唤醒策略
- 224浏览 收藏
-
- Golang · Go教程 | 7小时前 |
- Go sync.OnceValue 延迟初始化结果的复用方式
- 132浏览 收藏
-
- Golang · Go教程 | 7小时前 | go · Context · 并发编程 · Go context.WithoutCancel context取消传播
- Go context.WithoutCancel 脱离父取消的使用边界
- 396浏览 收藏
-
- Golang · Go教程 | 8小时前 | go · Context · 并发编程 · Go context.AfterFunc 幂等清理
- Go context.AfterFunc 取消回调的幂等设计
- 367浏览 收藏
-
- Golang · Go教程 | 8小时前 | 错误处理 · go · Context · Go context.WithCancelCause context.Cause
- Go context.WithCancelCause 传递根因的错误链
- 431浏览 收藏
-
- Golang · Go教程 | 9小时前 |
- Go ResponseController 设置写超时的适用边界
- 277浏览 收藏
-
- Golang · Go教程 | 9小时前 |
- Go encoding/csv Reader FieldsPerRecord 处理变长列
- 189浏览 收藏
-
- Golang · Go教程 | 2天前 | Go教程 · Go encoding/xml 空元素 指针字段
- Go encoding/xml 空元素与指针字段的处理方式
- 142浏览 收藏
-
- Golang · Go教程 | 2天前 | Go教程 · Go encoding/xml 字段映射 Unmarshaler
- Go encoding/xml 自定义 Unmarshaler 的字段映射
- 189浏览 收藏
查看更多
课程推荐
-
- 前端进阶之JavaScript设计模式
- 设计模式是开发人员在软件开发过程中面临一般问题时的解决方案,代表了最佳的实践。本课程的主打内容包括JS常见设计模式以及具体应用场景,打造一站式知识长龙服务,适合有JS基础的同学学习。
- 543次学习
-
- GO语言核心编程课程
- 本课程采用真实案例,全面具体可落地,从理论到实践,一步一步将GO核心编程技术、编程思想、底层实现融会贯通,使学习者贴近时代脉搏,做IT互联网时代的弄潮儿。
- 516次学习
-
- 简单聊聊mysql8与网络通信
- 如有问题加微信:Le-studyg;在课程中,我们将首先介绍MySQL8的新特性,包括性能优化、安全增强、新数据类型等,帮助学生快速熟悉MySQL8的最新功能。接着,我们将深入解析MySQL的网络通信机制,包括协议、连接管理、数据传输等,让
- 500次学习
-
- JavaScript正则表达式基础与实战
- 在任何一门编程语言中,正则表达式,都是一项重要的知识,它提供了高效的字符串匹配与捕获机制,可以极大的简化程序设计。
- 487次学习
-
- 从零制作响应式网站—Grid布局
- 本系列教程将展示从零制作一个假想的网络科技公司官网,分为导航,轮播,关于我们,成功案例,服务流程,团队介绍,数据部分,公司动态,底部信息等内容区块。网站整体采用CSSGrid布局,支持响应式,有流畅过渡和展现动画。
- 485次学习
查看更多
AI推荐
-
- PubMedQA
- 深入了解PubMedQA生物医学问答数据集,涵盖其核心功能、使用方法及在临床决策、药物研发等场景的应用,助力提升NLP模型性能。
- 291次使用
-
- H2O EvalGPT
- H2O EvalGPT是H2O.ai推出的开源LLM评估平台,提供详细的大模型性能排行榜、行业特定基准测试及A/B测试功能,助您快速选择最适合项目的高性能大语言模型。
- 344次使用
-
- LMArena
- LMArena是加州大学伯克利分校推出的AI模型匿名评测平台。通过盲测投票机制,用户可对比不同大模型回答并生成实时排行榜,助力开发者优化模型及用户选择最佳AI工具。
- 347次使用
-
- HELM
- 深入了解斯坦福推出的HELM(Holistic Evaluation of Language Models)大模型评测体系。本文解析其核心功能、安装配置步骤及应用场景,涵盖准确性、公平性、鲁棒性等多维度指标,助力开发者全面优化语言模型性能。
- 309次使用
-
- MMBench
- MMBench是由上海人工智能实验室等机构联合推出的多模态基准测试平台,提供细粒度能力评估、大规模数据集及VLMEvalKit工具。本文详细介绍其核心功能、安装使用方法及应用场景,助力开发者全面评估多模态模型性能。
- 131次使用
查看更多
相关文章
-
- Java 性能优化上线清单:从定位、改造到灰度发布
- 2026-06-11 860浏览
-
- Spring Boot 压测验证:Gatling、JMeter 与性能回归门禁
- 2026-06-11 843浏览
-
- Java NMT 非堆内存排查:Direct Buffer、线程栈与 Metaspace 分析
- 2026-06-11 826浏览
-
- Spring Boot 容器内存优化:JVM 堆、非堆与 MaxRAMPercentage
- 2026-06-11 809浏览
-
- Tomcat 连接与线程参数调优:maxThreads、acceptCount 与 KeepAlive
- 2026-06-11 792浏览
