使用Golang原生功能实现用户注册与登录,包含路由设计、表单处理、bcrypt密码哈希、SQLite存储及基于Cookie的Session管理,适合学习但生产环境需结合Redis与HTTPS增强安全。

用户注册与登录是大多数Web服务的基础功能。使用Golang实现这一功能并不复杂,关键在于合理设计路由、处理表单数据、安全存储密码以及管理会话。下面通过一个简单的实战项目,展示如何用原生Golang(不依赖框架)完成基础的用户注册与登录。
创建项目目录,例如 user-auth,结构如下:
├── main.go使用Go Modules初始化:
go mod init user-auth使用SQLite作为轻量数据库存储用户信息。在 db/db.go 中初始化数据库连接:
立即学习“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 }永远不要明文存储密码。使用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 }在 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) }使用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) }保护需要登录才能访问的页面,例如用户个人页:
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 示例:
<h1>欢迎,{{.}}!</h1> <a href="/logout">退出</a>清除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) }运行项目:go run main.go,访问 http://localhost:8080/register 开始测试。
基本上就这些。这个小项目涵盖了注册、登录、密码哈希、Session管理等核心要点。虽然用了内存存储Session,适合学习,实际生产建议结合Redis和HTTPS来提升安全性。
以上就是Golang如何实现基础的用户注册与登录_Golang用户注册登录项目实战的详细内容,更多请关注php中文网其它相关文章!
每个人都需要一台速度更快、更稳定的 PC。随着时间的推移,垃圾文件、旧注册表数据和不必要的后台进程会占用资源并降低性能。幸运的是,许多工具可以让 Windows 保持平稳运行。
Copyright 2014-2025 https://www.php.cn/ All Rights Reserved | php.cn | 湘ICP备2023035733号