feat(auth): 添加完整的用户认证API项目
- 实现用户注册、登录、JWT令牌认证功能 - 集成Gin、GORM、Viper、Zap等框架 - 添加密码加密、数据库操作、中间件等完整功能 - 配置多环境支持、日志轮转、CORS处理 - 创建完整的项目结构和配置文件体系
This commit is contained in:
8
Web开发/06go-auth-api/.idea/.gitignore
generated
vendored
Normal file
8
Web开发/06go-auth-api/.idea/.gitignore
generated
vendored
Normal file
@@ -0,0 +1,8 @@
|
||||
# 默认忽略的文件
|
||||
/shelf/
|
||||
/workspace.xml
|
||||
# 基于编辑器的 HTTP 客户端请求
|
||||
/httpRequests/
|
||||
# Datasource local storage ignored files
|
||||
/dataSources/
|
||||
/dataSources.local.xml
|
||||
9
Web开发/06go-auth-api/.idea/06go-auth-api.iml
generated
Normal file
9
Web开发/06go-auth-api/.idea/06go-auth-api.iml
generated
Normal file
@@ -0,0 +1,9 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<module type="WEB_MODULE" version="4">
|
||||
<component name="Go" enabled="true" />
|
||||
<component name="NewModuleRootManager">
|
||||
<content url="file://$MODULE_DIR$" />
|
||||
<orderEntry type="inheritedJdk" />
|
||||
<orderEntry type="sourceFolder" forTests="false" />
|
||||
</component>
|
||||
</module>
|
||||
20
Web开发/06go-auth-api/.idea/dataSources.xml
generated
Normal file
20
Web开发/06go-auth-api/.idea/dataSources.xml
generated
Normal file
@@ -0,0 +1,20 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourceManagerImpl" format="xml" multifile-model="true">
|
||||
<data-source source="LOCAL" name="auth" uuid="37ffb52c-594a-42a9-a7e1-f151f73e46f9">
|
||||
<driver-ref>sqlite.xerial</driver-ref>
|
||||
<synchronize>true</synchronize>
|
||||
<jdbc-driver>org.sqlite.JDBC</jdbc-driver>
|
||||
<jdbc-url>jdbc:sqlite:$PROJECT_DIR$/auth.db</jdbc-url>
|
||||
<working-dir>$ProjectFileDir$</working-dir>
|
||||
<libraries>
|
||||
<library>
|
||||
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/xerial/sqlite-jdbc/3.45.1.0/sqlite-jdbc-3.45.1.0.jar</url>
|
||||
</library>
|
||||
<library>
|
||||
<url>file://$APPLICATION_CONFIG_DIR$/jdbc-drivers/Xerial SQLiteJDBC/3.45.1/org/slf4j/slf4j-api/1.7.36/slf4j-api-1.7.36.jar</url>
|
||||
</library>
|
||||
</libraries>
|
||||
</data-source>
|
||||
</component>
|
||||
</project>
|
||||
6
Web开发/06go-auth-api/.idea/data_source_mapping.xml
generated
Normal file
6
Web开发/06go-auth-api/.idea/data_source_mapping.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="DataSourcePerFileMappings">
|
||||
<file url="file://$APPLICATION_CONFIG_DIR$/consoles/db/37ffb52c-594a-42a9-a7e1-f151f73e46f9/console.sql" value="37ffb52c-594a-42a9-a7e1-f151f73e46f9" />
|
||||
</component>
|
||||
</project>
|
||||
8
Web开发/06go-auth-api/.idea/modules.xml
generated
Normal file
8
Web开发/06go-auth-api/.idea/modules.xml
generated
Normal file
@@ -0,0 +1,8 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="ProjectModuleManager">
|
||||
<modules>
|
||||
<module fileurl="file://$PROJECT_DIR$/.idea/06go-auth-api.iml" filepath="$PROJECT_DIR$/.idea/06go-auth-api.iml" />
|
||||
</modules>
|
||||
</component>
|
||||
</project>
|
||||
6
Web开发/06go-auth-api/.idea/vcs.xml
generated
Normal file
6
Web开发/06go-auth-api/.idea/vcs.xml
generated
Normal file
@@ -0,0 +1,6 @@
|
||||
<?xml version="1.0" encoding="UTF-8"?>
|
||||
<project version="4">
|
||||
<component name="VcsDirectoryMappings">
|
||||
<mapping directory="$PROJECT_DIR$/../.." vcs="Git" />
|
||||
</component>
|
||||
</project>
|
||||
826
Web开发/06go-auth-api/21综合实战项目.md
Normal file
826
Web开发/06go-auth-api/21综合实战项目.md
Normal file
@@ -0,0 +1,826 @@
|
||||
---
|
||||
title: 综合实战项目
|
||||
icon: mdi:shield-account
|
||||
date: 2025-12-23
|
||||
category:
|
||||
- Go
|
||||
- 后端
|
||||
- 工程化
|
||||
- 实战项目
|
||||
tag:
|
||||
- API
|
||||
- 用户认证
|
||||
- 密码加密
|
||||
- JWT
|
||||
- 综合实战
|
||||
---
|
||||
|
||||
整合 Gin、GORM、Viper、Zap 等框架,开发一个完整的用户注册/登录 API。这个项目包含用户认证、密码加密、JWT 令牌和数据库操作,是学习 Go Web 开发的完美案例。
|
||||
|
||||
<!-- more -->
|
||||
|
||||
---
|
||||
|
||||
# Go 综合实战:用户注册/登录 API 完整指南
|
||||
|
||||
这是一个完整的 Web 应用示例,整合了前面学到的所有知识:Gin、GORM、Viper、Zap、中间件等。
|
||||
|
||||
---
|
||||
|
||||
## 一、项目结构
|
||||
|
||||
```
|
||||
go-auth-api/
|
||||
├── config/
|
||||
│ ├── app.yaml
|
||||
│ ├── app.dev.yaml
|
||||
│ └── app.prod.yaml
|
||||
├── logs/
|
||||
│ └── app.log
|
||||
├── main.go
|
||||
├── config.go
|
||||
├── logger.go
|
||||
├── db.go
|
||||
├── models.go
|
||||
├── handlers.go
|
||||
├── middleware.go
|
||||
├── jwt.go
|
||||
├── utils.go
|
||||
└── go.mod
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 二、项目初始化
|
||||
|
||||
### 2.1 创建项目
|
||||
|
||||
```bash
|
||||
cd ~/GolandProjects
|
||||
mkdir go-auth-api && cd go-auth-api
|
||||
go mod init go-auth-api
|
||||
|
||||
# 安装依赖
|
||||
go get -u github.com/gin-gonic/gin
|
||||
go get -u gorm.io/gorm
|
||||
go get -u gorm.io/driver/sqlite
|
||||
go get -u github.com/spf13/viper
|
||||
go get -u go.uber.org/zap
|
||||
go get -u github.com/golang-jwt/jwt/v4
|
||||
go get -u golang.org/x/crypto
|
||||
go get -u gopkg.in/natefinch/lumberjack.v2
|
||||
```
|
||||
|
||||
> **版本说明**:代码兼容 Go 1.18+ 版本(建议 1.22+ 体验最佳性能)
|
||||
|
||||
### 2.2 创建目录
|
||||
|
||||
```bash
|
||||
mkdir -p config logs
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 三、配置文件
|
||||
|
||||
### 3.1 config/app.yaml
|
||||
|
||||
```yaml
|
||||
app:
|
||||
name: AuthAPI
|
||||
version: 1.0.0
|
||||
port: 8080
|
||||
env: dev
|
||||
|
||||
database:
|
||||
driver: sqlite
|
||||
path: auth.db
|
||||
|
||||
jwt:
|
||||
secret: your-secret-key-change-in-production
|
||||
expire: 86400 # 24 小时
|
||||
|
||||
password:
|
||||
bcrypt_cost: 10
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: json
|
||||
```
|
||||
|
||||
### 3.2 config/app.prod.yaml
|
||||
|
||||
```yaml
|
||||
app:
|
||||
port: 80
|
||||
env: prod
|
||||
|
||||
logging:
|
||||
level: warn
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 四、模型定义(models.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Email string `gorm:"size:100;unique;not null" json:"email"`
|
||||
Password string `gorm:"size:255;not null" json:"-"` // 不在 JSON 中显示
|
||||
Phone string `gorm:"size:20" json:"phone,omitempty"`
|
||||
Age int `json:"age,omitempty"`
|
||||
Active bool `gorm:"default:true" json:"active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"-"`
|
||||
}
|
||||
|
||||
func (User) TableName() string {
|
||||
return "users"
|
||||
}
|
||||
|
||||
// 请求体
|
||||
type RegisterRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Phone string `json:"phone" binding:"omitempty,len=11"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 五、数据库初始化(db.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func InitDB(cfg *Config) error {
|
||||
var dsn string
|
||||
|
||||
if cfg.Database.Driver == "sqlite" {
|
||||
dsn = cfg.Database.Path
|
||||
}
|
||||
|
||||
var err error
|
||||
DB, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("failed to connect database: %w", err)
|
||||
}
|
||||
|
||||
// 自动迁移
|
||||
if err = DB.AutoMigrate(&User{}); err != nil {
|
||||
return fmt.Errorf("failed to migrate database: %w", err)
|
||||
}
|
||||
|
||||
Logger.Info("Database initialized successfully")
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 六、JWT 和密码工具(jwt.go + utils.go)
|
||||
|
||||
### 6.1 jwt.go
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GenerateToken(userID uint, email string, secret string, expire int64) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expire) * time.Second)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
func VerifyToken(tokenString string, secret string) (*Claims, error) {
|
||||
claims := &Claims{}
|
||||
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
if !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
}
|
||||
```
|
||||
|
||||
### 6.2 utils.go
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// 密码加密
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
func VerifyPassword(hashedPassword, password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// 检查邮箱是否已注册
|
||||
func EmailExists(email string) bool {
|
||||
var count int64
|
||||
DB.Model(&User{}).Where("email = ?", email).Count(&count)
|
||||
return count > 0
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 七、中间件(middleware.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// 请求日志中间件
|
||||
func LoggingMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
Logger.Info("Request",
|
||||
zap.String("method", c.Request.Method),
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.String("ip", c.ClientIP()),
|
||||
)
|
||||
|
||||
c.Next()
|
||||
|
||||
Logger.Info("Response",
|
||||
zap.String("path", c.Request.URL.Path),
|
||||
zap.Int("status", c.Writer.Status()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// JWT 认证中间件
|
||||
func AuthMiddleware(cfg *Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
|
||||
if authHeader == "" {
|
||||
c.JSON(401, gin.H{"error": "Missing authorization header"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
c.JSON(401, gin.H{"error": "Invalid authorization header"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
claims, err := VerifyToken(parts[1], cfg.JWT.Secret)
|
||||
if err != nil {
|
||||
Logger.Error("Token verification failed", zap.Error(err))
|
||||
c.JSON(401, gin.H{"error": "Invalid token"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 将用户信息存储在上下文中
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("email", claims.Email)
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// CORS 中间件
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 八、业务逻辑处理器(handlers.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// 注册用户
|
||||
func Register(cfg *Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req RegisterRequest
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
Logger.Error("Invalid registration request", zap.Error(err))
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 检查邮箱是否已存在
|
||||
if EmailExists(req.Email) {
|
||||
c.JSON(400, gin.H{"error": "Email already registered"})
|
||||
return
|
||||
}
|
||||
|
||||
// 密码加密
|
||||
hashedPassword, err := HashPassword(req.Password)
|
||||
if err != nil {
|
||||
Logger.Error("Failed to hash password", zap.Error(err))
|
||||
c.JSON(500, gin.H{"error": "Internal server error"})
|
||||
return
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
user := User{
|
||||
Name: req.Name,
|
||||
Email: req.Email,
|
||||
Password: hashedPassword,
|
||||
Phone: req.Phone,
|
||||
}
|
||||
|
||||
if err := DB.Create(&user).Error; err != nil {
|
||||
Logger.Error("Failed to create user", zap.Error(err))
|
||||
c.JSON(500, gin.H{"error": "Failed to register user"})
|
||||
return
|
||||
}
|
||||
|
||||
Logger.Info("User registered successfully", zap.String("email", user.Email))
|
||||
|
||||
c.JSON(201, gin.H{
|
||||
"message": "User registered successfully",
|
||||
"user_id": user.ID,
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 用户登录
|
||||
func Login(cfg *Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req LoginRequest
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
// 查找用户
|
||||
var user User
|
||||
if err := DB.Where("email = ?", req.Email).First(&user).Error; err != nil {
|
||||
Logger.Warn("User not found", zap.String("email", req.Email))
|
||||
c.JSON(401, gin.H{"error": "Invalid email or password"})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证密码
|
||||
if !VerifyPassword(user.Password, req.Password) {
|
||||
Logger.Warn("Invalid password", zap.String("email", req.Email))
|
||||
c.JSON(401, gin.H{"error": "Invalid email or password"})
|
||||
return
|
||||
}
|
||||
|
||||
// 生成 JWT token
|
||||
token, err := GenerateToken(user.ID, user.Email, cfg.JWT.Secret, int64(cfg.JWT.Expire))
|
||||
if err != nil {
|
||||
Logger.Error("Failed to generate token", zap.Error(err))
|
||||
c.JSON(500, gin.H{"error": "Failed to generate token"})
|
||||
return
|
||||
}
|
||||
|
||||
Logger.Info("User logged in successfully", zap.String("email", user.Email))
|
||||
|
||||
c.JSON(200, LoginResponse{
|
||||
Token: token,
|
||||
User: User{
|
||||
ID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
Phone: user.Phone,
|
||||
Age: user.Age,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
func GetProfile(c *gin.Context) {
|
||||
userID, _ := c.Get("user_id")
|
||||
|
||||
var user User
|
||||
if err := DB.First(&user, userID.(uint)).Error; err != nil {
|
||||
c.JSON(404, gin.H{"error": "User not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, user)
|
||||
}
|
||||
|
||||
// 更新用户信息
|
||||
func UpdateProfile(c *gin.Context) {
|
||||
userID, _ := c.Get("user_id")
|
||||
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Phone string `json:"phone"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := DB.Model(&User{}).Where("id = ?", userID.(uint)).Updates(req).Error; err != nil {
|
||||
Logger.Error("Failed to update user", zap.Error(err))
|
||||
c.JSON(500, gin.H{"error": "Failed to update profile"})
|
||||
return
|
||||
}
|
||||
|
||||
Logger.Info("User profile updated", zap.Uint("user_id", userID.(uint)))
|
||||
c.JSON(200, gin.H{"message": "Profile updated successfully"})
|
||||
}
|
||||
|
||||
// 健康检查
|
||||
func HealthCheck(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"status": "ok",
|
||||
"app": "AuthAPI",
|
||||
})
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 九、配置加载(config.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
App struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Version string `mapstructure:"version"`
|
||||
Port int `mapstructure:"port"`
|
||||
Env string `mapstructure:"env"`
|
||||
} `mapstructure:"app"`
|
||||
|
||||
Database struct {
|
||||
Driver string `mapstructure:"driver"`
|
||||
Path string `mapstructure:"path"`
|
||||
} `mapstructure:"database"`
|
||||
|
||||
JWT struct {
|
||||
Secret string `mapstructure:"secret"`
|
||||
Expire int `mapstructure:"expire"`
|
||||
} `mapstructure:"jwt"`
|
||||
|
||||
Logging struct {
|
||||
Level string `mapstructure:"level"`
|
||||
Format string `mapstructure:"format"`
|
||||
} `mapstructure:"logging"`
|
||||
}
|
||||
|
||||
var GlobalConfig *Config
|
||||
|
||||
func LoadConfig() (*Config, error) {
|
||||
env := os.Getenv("GO_ENV")
|
||||
if env == "" {
|
||||
env = "dev"
|
||||
}
|
||||
|
||||
viper.SetConfigName("app")
|
||||
viper.SetConfigType("yaml")
|
||||
viper.AddConfigPath("./config")
|
||||
|
||||
if err := viper.ReadInConfig(); err != nil {
|
||||
return nil, fmt.Errorf("failed to read config: %w", err)
|
||||
}
|
||||
|
||||
viper.SetConfigName("app." + env)
|
||||
viper.MergeInConfig()
|
||||
|
||||
var cfg Config
|
||||
if err := viper.Unmarshal(&cfg); err != nil {
|
||||
return nil, fmt.Errorf("failed to unmarshal config: %w", err)
|
||||
}
|
||||
|
||||
GlobalConfig = &cfg
|
||||
return &cfg, nil
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十、日志初始化(logger.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
var Logger *zap.Logger
|
||||
|
||||
func InitLogger(env string) error {
|
||||
var level zapcore.Level
|
||||
|
||||
switch env {
|
||||
case "prod":
|
||||
level = zapcore.WarnLevel
|
||||
case "test":
|
||||
level = zapcore.DebugLevel
|
||||
default:
|
||||
level = zapcore.InfoLevel
|
||||
}
|
||||
|
||||
logFile := &lumberjack.Logger{
|
||||
Filename: "logs/app.log",
|
||||
MaxSize: 100,
|
||||
MaxBackups: 10,
|
||||
MaxAge: 7,
|
||||
Compress: true,
|
||||
}
|
||||
|
||||
encoderConfig := zapcore.EncoderConfig{
|
||||
TimeKey: "ts",
|
||||
LevelKey: "level",
|
||||
MessageKey: "msg",
|
||||
CallerKey: "caller",
|
||||
EncodeLevel: zapcore.LowercaseLevelEncoder,
|
||||
EncodeTime: zapcore.ISO8601TimeEncoder,
|
||||
EncodeCaller: zapcore.ShortCallerEncoder,
|
||||
}
|
||||
|
||||
core := zapcore.NewCore(
|
||||
zapcore.NewJSONEncoder(encoderConfig),
|
||||
zapcore.NewMultiWriteSyncer(
|
||||
zapcore.AddSync(os.Stdout),
|
||||
zapcore.AddSync(logFile),
|
||||
),
|
||||
level,
|
||||
)
|
||||
|
||||
Logger = zap.New(core, zap.AddCaller())
|
||||
zap.ReplaceGlobals(Logger)
|
||||
|
||||
return nil
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十一、主程序(main.go)
|
||||
|
||||
```go
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// 加载配置
|
||||
cfg, err := LoadConfig()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
// 初始化日志
|
||||
if err = InitLogger(cfg.App.Env); err != nil {
|
||||
panic(err)
|
||||
}
|
||||
defer Logger.Sync()
|
||||
|
||||
// 初始化数据库
|
||||
if err = InitDB(cfg); err != nil {
|
||||
Logger.Fatal("Failed to initialize database", zap.Error(err))
|
||||
}
|
||||
|
||||
// 创建 Gin 应用
|
||||
r := gin.Default()
|
||||
|
||||
// 应用中间件
|
||||
r.Use(LoggingMiddleware())
|
||||
r.Use(CORSMiddleware())
|
||||
|
||||
// 公开路由
|
||||
public := r.Group("/api")
|
||||
{
|
||||
public.GET("/health", HealthCheck)
|
||||
public.POST("/register", Register(cfg))
|
||||
public.POST("/login", Login(cfg))
|
||||
}
|
||||
|
||||
// 受保护的路由
|
||||
protected := r.Group("/api")
|
||||
protected.Use(AuthMiddleware(cfg))
|
||||
{
|
||||
protected.GET("/profile", GetProfile)
|
||||
protected.PUT("/profile", UpdateProfile)
|
||||
}
|
||||
|
||||
// 启动服务器
|
||||
addr := fmt.Sprintf(":%d", cfg.App.Port)
|
||||
Logger.Info("Server starting",
|
||||
zap.String("app", cfg.App.Name),
|
||||
zap.Int("port", cfg.App.Port),
|
||||
zap.String("env", cfg.App.Env),
|
||||
)
|
||||
|
||||
if err = r.Run(addr); err != nil {
|
||||
Logger.Fatal("Server error", zap.Error(err))
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十二、API 使用示例
|
||||
|
||||
### 12.1 注册用户
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/api/register \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"name": "Alice",
|
||||
"email": "alice@example.com",
|
||||
"password": "password123",
|
||||
"phone": "13800138000"
|
||||
}'
|
||||
|
||||
# 响应
|
||||
{
|
||||
"message": "User registered successfully",
|
||||
"user_id": 1
|
||||
}
|
||||
```
|
||||
|
||||
### 12.2 用户登录
|
||||
|
||||
```bash
|
||||
curl -X POST http://localhost:8080/api/login \
|
||||
-H "Content-Type: application/json" \
|
||||
-d '{
|
||||
"email": "alice@example.com",
|
||||
"password": "password123"
|
||||
}'
|
||||
|
||||
# 响应
|
||||
{
|
||||
"token": "eyJhbGciOiJIUzI1NiIs...",
|
||||
"user": {
|
||||
"id": 1,
|
||||
"name": "Alice",
|
||||
"email": "alice@example.com",
|
||||
"phone": "13800138000"
|
||||
}
|
||||
}
|
||||
```
|
||||
|
||||
### 12.3 获取用户信息(需要认证)
|
||||
|
||||
```bash
|
||||
curl -X GET http://localhost:8080/api/profile \
|
||||
-H "Authorization: Bearer eyJhbGciOiJIUzI1NiIs..."
|
||||
|
||||
# 响应
|
||||
{
|
||||
"id": 1,
|
||||
"name": "Alice",
|
||||
"email": "alice@example.com",
|
||||
"phone": "13800138000",
|
||||
"age": 0,
|
||||
"active": true,
|
||||
"created_at": "2025-12-23T14:30:45Z"
|
||||
}
|
||||
```
|
||||
|
||||
---
|
||||
|
||||
## 十三、项目验收清单
|
||||
|
||||
- ✅ 用户注册(密码加密、邮箱验证)
|
||||
- ✅ 用户登录(JWT 令牌生成)
|
||||
- ✅ 用户认证(JWT 验证中间件)
|
||||
- ✅ 用户信息管理(获取、更新)
|
||||
- ✅ 配置管理(多环境)
|
||||
- ✅ 日志记录(结构化、日志轮转)
|
||||
- ✅ 错误处理(友好的错误消息)
|
||||
- ✅ 代码组织(清晰的文件结构)
|
||||
|
||||
---
|
||||
|
||||
## 十四、进阶扩展方向
|
||||
|
||||
1. **添加邮箱验证** - 发送验证码验证邮箱
|
||||
2. **实现刷新令牌** - 增加安全性
|
||||
3. **添加速率限制** - 防止暴力破解
|
||||
4. **用户权限管理** - 基于角色的访问控制
|
||||
5. **社交登录** - 集成 OAuth2(GitHub、Google)
|
||||
6. **单元测试** - 为关键业务逻辑编写测试
|
||||
7. **Docker 打包** - 容器化部署
|
||||
8. **CI/CD 流程** - 自动化测试和部署
|
||||
|
||||
---
|
||||
|
||||
祝你编码愉快!🚀 这个项目整合了 Go Web 开发的所有核心知识,是学习和面试的好材料。
|
||||
|
||||
BIN
Web开发/06go-auth-api/auth.db
Normal file
BIN
Web开发/06go-auth-api/auth.db
Normal file
Binary file not shown.
60
Web开发/06go-auth-api/config.go
Normal file
60
Web开发/06go-auth-api/config.go
Normal file
@@ -0,0 +1,60 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"os"
|
||||
|
||||
"github.com/spf13/viper"
|
||||
)
|
||||
|
||||
type Config struct {
|
||||
App struct {
|
||||
Name string `mapstructure:"name"`
|
||||
Version string `mapstructure:"version"`
|
||||
Port int `mapstructure:"port"`
|
||||
Env string `mapstructure:"env"`
|
||||
} `mapstructure:"app"`
|
||||
|
||||
Database struct {
|
||||
Driver string `mapstructure:"driver"`
|
||||
Path string `mapstructure:"path"`
|
||||
} `mapstructure:"database"`
|
||||
|
||||
JWT struct {
|
||||
Secret string `mapstructure:"secret"`
|
||||
Expire int `mapstructure:"expire"`
|
||||
} `mapstructure:"jwt"`
|
||||
|
||||
Logging struct {
|
||||
Level string `mapstructure:"level"`
|
||||
Format string `mapstructure:"format"`
|
||||
} `mapstructure:"logging"`
|
||||
}
|
||||
|
||||
var GlobalConfig *Config
|
||||
|
||||
func LoadConfig() (*Config, error) {
|
||||
env := os.Getenv("APP_ENV")
|
||||
if env == "" {
|
||||
env = "dev"
|
||||
}
|
||||
|
||||
viper.SetConfigName("app")
|
||||
viper.AddConfigPath("./config")
|
||||
viper.SetConfigType("yaml")
|
||||
|
||||
err := viper.ReadInConfig()
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("读取配置文件失败: %w", err)
|
||||
}
|
||||
|
||||
viper.SetConfigName("app." + env)
|
||||
err = viper.MergeInConfig()
|
||||
var cfg Config
|
||||
err = viper.Unmarshal(&cfg)
|
||||
if err != nil {
|
||||
return nil, fmt.Errorf("解析配置文件失败: %w", err)
|
||||
}
|
||||
GlobalConfig = &cfg
|
||||
return &cfg, nil
|
||||
}
|
||||
6
Web开发/06go-auth-api/config/app.prod.yaml
Normal file
6
Web开发/06go-auth-api/config/app.prod.yaml
Normal file
@@ -0,0 +1,6 @@
|
||||
app:
|
||||
port: 80
|
||||
env: prod
|
||||
|
||||
logging:
|
||||
level: warn
|
||||
20
Web开发/06go-auth-api/config/app.yaml
Normal file
20
Web开发/06go-auth-api/config/app.yaml
Normal file
@@ -0,0 +1,20 @@
|
||||
app:
|
||||
name: AuthAPI
|
||||
version: 1.0.0
|
||||
port: 8088
|
||||
env: dev
|
||||
|
||||
database:
|
||||
driver: sqlite
|
||||
path: auth.db
|
||||
|
||||
jwt:
|
||||
secret: your-secret-key-change-in-production
|
||||
expire: 86400 # 24 小时
|
||||
|
||||
password:
|
||||
bcrypt_cost: 10
|
||||
|
||||
logging:
|
||||
level: info
|
||||
format: json
|
||||
32
Web开发/06go-auth-api/db.go
Normal file
32
Web开发/06go-auth-api/db.go
Normal file
@@ -0,0 +1,32 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"gorm.io/driver/sqlite"
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
var DB *gorm.DB
|
||||
|
||||
func InitDB(cfg *Config) error {
|
||||
var dsn string
|
||||
if cfg.Database.Driver == "sqlite" {
|
||||
dsn = cfg.Database.Path
|
||||
}
|
||||
|
||||
var err error
|
||||
DB, err = gorm.Open(sqlite.Open(dsn), &gorm.Config{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("连接数据库失败: %w", err)
|
||||
}
|
||||
|
||||
//自动迁移
|
||||
err = DB.AutoMigrate(&User{})
|
||||
if err != nil {
|
||||
return fmt.Errorf("自动迁移数据库失败: %w", err)
|
||||
}
|
||||
|
||||
Logger.Info("数据库初始化成功")
|
||||
return nil
|
||||
}
|
||||
62
Web开发/06go-auth-api/go.mod
Normal file
62
Web开发/06go-auth-api/go.mod
Normal file
@@ -0,0 +1,62 @@
|
||||
module go-auth-api
|
||||
|
||||
go 1.22.2
|
||||
|
||||
require (
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2
|
||||
go.uber.org/zap v1.27.0
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1
|
||||
gorm.io/driver/sqlite v1.5.6
|
||||
gorm.io/gorm v1.25.7
|
||||
)
|
||||
|
||||
require (
|
||||
github.com/bytedance/sonic v1.11.6 // indirect
|
||||
github.com/bytedance/sonic/loader v0.1.1 // indirect
|
||||
github.com/cloudwego/base64x v0.1.4 // indirect
|
||||
github.com/cloudwego/iasm v0.2.0 // indirect
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc // indirect
|
||||
github.com/fsnotify/fsnotify v1.7.0 // indirect
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 // indirect
|
||||
github.com/gin-contrib/sse v0.1.0 // indirect
|
||||
github.com/gin-gonic/gin v1.10.0 // indirect
|
||||
github.com/go-playground/locales v0.14.1 // indirect
|
||||
github.com/go-playground/universal-translator v0.18.1 // indirect
|
||||
github.com/go-playground/validator/v10 v10.20.0 // indirect
|
||||
github.com/goccy/go-json v0.10.2 // indirect
|
||||
github.com/hashicorp/hcl v1.0.0 // indirect
|
||||
github.com/jinzhu/inflection v1.0.0 // indirect
|
||||
github.com/jinzhu/now v1.1.5 // indirect
|
||||
github.com/json-iterator/go v1.1.12 // indirect
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 // indirect
|
||||
github.com/leodido/go-urn v1.4.0 // indirect
|
||||
github.com/magiconair/properties v1.8.7 // indirect
|
||||
github.com/mattn/go-isatty v0.0.20 // indirect
|
||||
github.com/mattn/go-sqlite3 v1.14.22 // indirect
|
||||
github.com/mitchellh/mapstructure v1.5.0 // indirect
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd // indirect
|
||||
github.com/modern-go/reflect2 v1.0.2 // indirect
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 // indirect
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 // indirect
|
||||
github.com/sagikazarmark/locafero v0.4.0 // indirect
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 // indirect
|
||||
github.com/sourcegraph/conc v0.3.0 // indirect
|
||||
github.com/spf13/afero v1.11.0 // indirect
|
||||
github.com/spf13/cast v1.6.0 // indirect
|
||||
github.com/spf13/pflag v1.0.5 // indirect
|
||||
github.com/spf13/viper v1.18.2 // indirect
|
||||
github.com/stretchr/testify v1.9.0 // indirect
|
||||
github.com/subosito/gotenv v1.6.0 // indirect
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 // indirect
|
||||
github.com/ugorji/go/codec v1.2.12 // indirect
|
||||
go.uber.org/multierr v1.10.0 // indirect
|
||||
golang.org/x/arch v0.8.0 // indirect
|
||||
golang.org/x/crypto v0.23.0 // indirect
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 // indirect
|
||||
golang.org/x/net v0.25.0 // indirect
|
||||
golang.org/x/sys v0.20.0 // indirect
|
||||
golang.org/x/text v0.15.0 // indirect
|
||||
google.golang.org/protobuf v1.34.1 // indirect
|
||||
gopkg.in/ini.v1 v1.67.0 // indirect
|
||||
gopkg.in/yaml.v3 v3.0.1 // indirect
|
||||
)
|
||||
134
Web开发/06go-auth-api/go.sum
Normal file
134
Web开发/06go-auth-api/go.sum
Normal file
@@ -0,0 +1,134 @@
|
||||
github.com/bytedance/sonic v1.11.6 h1:oUp34TzMlL+OY1OUWxHqsdkgC/Zfc85zGqw9siXjrc0=
|
||||
github.com/bytedance/sonic v1.11.6/go.mod h1:LysEHSvpvDySVdC2f87zGWf6CIKJcAvqab1ZaiQtds4=
|
||||
github.com/bytedance/sonic/loader v0.1.1 h1:c+e5Pt1k/cy5wMveRDyk2X4B9hF4g7an8N3zCYjJFNM=
|
||||
github.com/bytedance/sonic/loader v0.1.1/go.mod h1:ncP89zfokxS5LZrJxl5z0UJcsk4M4yY2JpfqGeCtNLU=
|
||||
github.com/cloudwego/base64x v0.1.4 h1:jwCgWpFanWmN8xoIUHa2rtzmkd5J2plF/dnLS6Xd/0Y=
|
||||
github.com/cloudwego/base64x v0.1.4/go.mod h1:0zlkT4Wn5C6NdauXdJRhSKRlJvmclQ1hhJgA0rcu/8w=
|
||||
github.com/cloudwego/iasm v0.2.0 h1:1KNIy1I1H9hNNFEEH3DVnI4UujN+1zjpuk6gwHLTssg=
|
||||
github.com/cloudwego/iasm v0.2.0/go.mod h1:8rXZaNYT2n95jn+zTI1sDr+IgcD2GVs0nlbbQPiEFhY=
|
||||
github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc h1:U9qPSI2PIWSS1VwoXQT9A3Wy9MM3WgvqSxFWenqJduM=
|
||||
github.com/davecgh/go-spew v1.1.2-0.20180830191138-d8f796af33cc/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38=
|
||||
github.com/fsnotify/fsnotify v1.7.0 h1:8JEhPFa5W2WU7YfeZzPNqzMP6Lwt7L2715Ggo0nosvA=
|
||||
github.com/fsnotify/fsnotify v1.7.0/go.mod h1:40Bi/Hjc2AVfZrqy+aj+yEI+/bRxZnMJyTJwOpGvigM=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3 h1:in2uUcidCuFcDKtdcBxlR0rJ1+fsokWf+uqxgUFjbI0=
|
||||
github.com/gabriel-vasile/mimetype v1.4.3/go.mod h1:d8uq/6HKRL6CGdk+aubisF/M5GcPfT7nKyLpA0lbSSk=
|
||||
github.com/gin-contrib/sse v0.1.0 h1:Y/yl/+YNO8GZSjAhjMsSuLt29uWRFHdHYUb5lYOV9qE=
|
||||
github.com/gin-contrib/sse v0.1.0/go.mod h1:RHrZQHXnP2xjPF+u1gW/2HnVO7nvIa9PG3Gm+fLHvGI=
|
||||
github.com/gin-gonic/gin v1.10.0 h1:nTuyha1TYqgedzytsKYqna+DfLos46nTv2ygFy86HFU=
|
||||
github.com/gin-gonic/gin v1.10.0/go.mod h1:4PMNQiOhvDRa013RKVbsiNwoyezlm2rm0uX/T7kzp5Y=
|
||||
github.com/go-playground/locales v0.14.1 h1:EWaQ/wswjilfKLTECiXz7Rh+3BjFhfDFKv/oXslEjJA=
|
||||
github.com/go-playground/locales v0.14.1/go.mod h1:hxrqLVvrK65+Rwrd5Fc6F2O76J/NuW9t0sjnWqG1slY=
|
||||
github.com/go-playground/universal-translator v0.18.1 h1:Bcnm0ZwsGyWbCzImXv+pAJnYK9S473LQFuzCbDbfSFY=
|
||||
github.com/go-playground/universal-translator v0.18.1/go.mod h1:xekY+UJKNuX9WP91TpwSH2VMlDf28Uj24BCp08ZFTUY=
|
||||
github.com/go-playground/validator/v10 v10.20.0 h1:K9ISHbSaI0lyB2eWMPJo+kOS/FBExVwjEviJTixqxL8=
|
||||
github.com/go-playground/validator/v10 v10.20.0/go.mod h1:dbuPbCMFw/DrkbEynArYaCwl3amGuJotoKCe95atGMM=
|
||||
github.com/goccy/go-json v0.10.2 h1:CrxCmQqYDkv1z7lO7Wbh2HN93uovUHgrECaO5ZrCXAU=
|
||||
github.com/goccy/go-json v0.10.2/go.mod h1:6MelG93GURQebXPDq3khkgXZkazVtN9CRI+MGFi0w8I=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2 h1:YtQM7lnr8iZ+j5q71MGKkNw9Mn7AjHM68uc9g5fXeUI=
|
||||
github.com/golang-jwt/jwt/v4 v4.5.2/go.mod h1:m21LjoU+eqJr34lmDMbreY2eSTRJ1cv77w39/MY0Ch0=
|
||||
github.com/google/gofuzz v1.0.0/go.mod h1:dBl0BpW6vV/+mYPU4Po3pmUjxk6FQPldtuIdl/M65Eg=
|
||||
github.com/hashicorp/hcl v1.0.0 h1:0Anlzjpi4vEasTeNFn2mLJgTSwt0+6sfsiTG8qcWGx4=
|
||||
github.com/hashicorp/hcl v1.0.0/go.mod h1:E5yfLk+7swimpb2L/Alb/PJmXilQ/rhwaUYs4T20WEQ=
|
||||
github.com/jinzhu/inflection v1.0.0 h1:K317FqzuhWc8YvSVlFMCCUb36O/S9MCKRDI7QkRKD/E=
|
||||
github.com/jinzhu/inflection v1.0.0/go.mod h1:h+uFLlag+Qp1Va5pdKtLDYj+kHp5pxUVkryuEj+Srlc=
|
||||
github.com/jinzhu/now v1.1.5 h1:/o9tlHleP7gOFmsnYNz3RGnqzefHA47wQpKrrdTIwXQ=
|
||||
github.com/jinzhu/now v1.1.5/go.mod h1:d3SSVoowX0Lcu0IBviAWJpolVfI5UJVZZ7cO71lE/z8=
|
||||
github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnrnM=
|
||||
github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo=
|
||||
github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7 h1:ZWSB3igEs+d0qvnxR/ZBzXVmxkgt8DdzP6m9pfuVLDM=
|
||||
github.com/klauspost/cpuid/v2 v2.2.7/go.mod h1:Lcz8mBdAVJIBVzewtcLocK12l3Y+JytZYpaMropDUws=
|
||||
github.com/knz/go-libedit v1.10.1/go.mod h1:MZTVkCWyz0oBc7JOWP3wNAzd002ZbM/5hgShxwh4x8M=
|
||||
github.com/leodido/go-urn v1.4.0 h1:WT9HwE9SGECu3lg4d/dIA+jxlljEa1/ffXKmRjqdmIQ=
|
||||
github.com/leodido/go-urn v1.4.0/go.mod h1:bvxc+MVxLKB4z00jd1z+Dvzr47oO32F/QSNjSBOlFxI=
|
||||
github.com/magiconair/properties v1.8.7 h1:IeQXZAiQcpL9mgcAe1Nu6cX9LLw6ExEHKjN0VQdvPDY=
|
||||
github.com/magiconair/properties v1.8.7/go.mod h1:Dhd985XPs7jluiymwWYZ0G4Z61jb3vdS329zhj2hYo0=
|
||||
github.com/mattn/go-isatty v0.0.20 h1:xfD0iDuEKnDkl03q4limB+vH+GxLEtL/jb4xVJSWWEY=
|
||||
github.com/mattn/go-isatty v0.0.20/go.mod h1:W+V8PltTTMOvKvAeJH7IuucS94S2C6jfK/D7dTCTo3Y=
|
||||
github.com/mattn/go-sqlite3 v1.14.22 h1:2gZY6PC6kBnID23Tichd1K+Z0oS6nE/XwU+Vz/5o4kU=
|
||||
github.com/mattn/go-sqlite3 v1.14.22/go.mod h1:Uh1q+B4BYcTPb+yiD3kU8Ct7aC0hY9fxUwlHK0RXw+Y=
|
||||
github.com/mitchellh/mapstructure v1.5.0 h1:jeMsZIYE/09sWLaz43PL7Gy6RuMjD2eJVyuac5Z2hdY=
|
||||
github.com/mitchellh/mapstructure v1.5.0/go.mod h1:bFUtVrKA4DC2yAKiSyO/QUcy7e+RRV2QTWOzhPopBRo=
|
||||
github.com/modern-go/concurrent v0.0.0-20180228061459-e0a39a4cb421/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd h1:TRLaZ9cD/w8PVh93nsPXa1VrQ6jlwL5oN8l14QlcNfg=
|
||||
github.com/modern-go/concurrent v0.0.0-20180306012644-bacd9c7ef1dd/go.mod h1:6dJC0mAP4ikYIbvyc7fijjWJddQyLn8Ig3JB5CqoB9Q=
|
||||
github.com/modern-go/reflect2 v1.0.2 h1:xBagoLtFs94CBntxluKeaWgTMpvLxC4ur3nMaC9Gz0M=
|
||||
github.com/modern-go/reflect2 v1.0.2/go.mod h1:yWuevngMOJpCy52FWWMvUC8ws7m/LJsjYzDa0/r8luk=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2 h1:aYUidT7k73Pcl9nb2gScu7NSrKCSHIDE89b3+6Wq+LM=
|
||||
github.com/pelletier/go-toml/v2 v2.2.2/go.mod h1:1t835xjRzz80PqgE6HHgN2JOsmgYu/h4qDAS4n929Rs=
|
||||
github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2 h1:Jamvg5psRIccs7FGNTlIRMkT8wgtp5eCXdBlqhYGL6U=
|
||||
github.com/pmezard/go-difflib v1.0.1-0.20181226105442-5d4384ee4fb2/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4=
|
||||
github.com/sagikazarmark/locafero v0.4.0 h1:HApY1R9zGo4DBgr7dqsTH/JJxLTTsOt7u6keLGt6kNQ=
|
||||
github.com/sagikazarmark/locafero v0.4.0/go.mod h1:Pe1W6UlPYUk/+wc/6KFhbORCfqzgYEpgQ3O5fPuL3H4=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0 h1:diDBnUNK9N/354PgrxMywXnAwEr1QZcOr6gto+ugjYE=
|
||||
github.com/sagikazarmark/slog-shim v0.1.0/go.mod h1:SrcSrq8aKtyuqEI1uvTDTK1arOWRIczQRv+GVI1AkeQ=
|
||||
github.com/sourcegraph/conc v0.3.0 h1:OQTbbt6P72L20UqAkXXuLOj79LfEanQ+YQFNpLA9ySo=
|
||||
github.com/sourcegraph/conc v0.3.0/go.mod h1:Sdozi7LEKbFPqYX2/J+iBAM6HpqSLTASQIKqDmF7Mt0=
|
||||
github.com/spf13/afero v1.11.0 h1:WJQKhtpdm3v2IzqG8VMqrr6Rf3UYpEF239Jy9wNepM8=
|
||||
github.com/spf13/afero v1.11.0/go.mod h1:GH9Y3pIexgf1MTIWtNGyogA5MwRIDXGUr+hbWNoBjkY=
|
||||
github.com/spf13/cast v1.6.0 h1:GEiTHELF+vaR5dhz3VqZfFSzZjYbgeKDpBxQVS4GYJ0=
|
||||
github.com/spf13/cast v1.6.0/go.mod h1:ancEpBxwJDODSW/UG4rDrAqiKolqNNh2DX3mk86cAdo=
|
||||
github.com/spf13/pflag v1.0.5 h1:iy+VFUOCP1a+8yFto/drg2CJ5u0yRoB7fZw3DKv/JXA=
|
||||
github.com/spf13/pflag v1.0.5/go.mod h1:McXfInJRrz4CZXVZOBLb0bTZqETkiAhM9Iw0y3An2Bg=
|
||||
github.com/spf13/viper v1.18.2 h1:LUXCnvUvSM6FXAsj6nnfc8Q2tp1dIgUfY9Kc8GsSOiQ=
|
||||
github.com/spf13/viper v1.18.2/go.mod h1:EKmWIqdnk5lOcmR72yw6hS+8OPYcwD0jteitLMVB+yk=
|
||||
github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME=
|
||||
github.com/stretchr/objx v0.4.0/go.mod h1:YvHI0jy2hoMjB+UWwv71VJQ9isScKT/TqJzVSSt89Yw=
|
||||
github.com/stretchr/objx v0.5.0/go.mod h1:Yh+to48EsGEfYuaHDzXPcE3xhTkx73EhmCGUpEOglKo=
|
||||
github.com/stretchr/objx v0.5.2/go.mod h1:FRsXN1f5AsAjCGJKqEizvkpNtU+EGNCLh3NxZ/8L+MA=
|
||||
github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI=
|
||||
github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.7.1/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg=
|
||||
github.com/stretchr/testify v1.8.0/go.mod h1:yNjHg4UonilssWZ8iaSj1OCr/vHnekPRkoO+kdMU+MU=
|
||||
github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4=
|
||||
github.com/stretchr/testify v1.8.4/go.mod h1:sz/lmYIOXD/1dqDmKjjqLyZ2RngseejIcXlSw2iwfAo=
|
||||
github.com/stretchr/testify v1.9.0 h1:HtqpIVDClZ4nwg75+f6Lvsy/wHu+3BoSGCbBAcpTsTg=
|
||||
github.com/stretchr/testify v1.9.0/go.mod h1:r2ic/lqez/lEtzL7wO/rwa5dbSLXVDPFyf8C91i36aY=
|
||||
github.com/subosito/gotenv v1.6.0 h1:9NlTDc1FTs4qu0DDq7AEtTPNw6SVm7uBMsUCUjABIf8=
|
||||
github.com/subosito/gotenv v1.6.0/go.mod h1:Dk4QP5c2W3ibzajGcXpNraDfq2IrhjMIvMSWPKKo0FU=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1 h1:SU5vSMR7hnwNxj24w34ZyCi/FmDZTkS4MhqMhdFk5YI=
|
||||
github.com/twitchyliquid64/golang-asm v0.15.1/go.mod h1:a1lVb/DtPvCB8fslRZhAngC2+aY1QWCk3Cedj/Gdt08=
|
||||
github.com/ugorji/go/codec v1.2.12 h1:9LC83zGrHhuUA9l16C9AHXAqEV/2wBQ4nkvumAE65EE=
|
||||
github.com/ugorji/go/codec v1.2.12/go.mod h1:UNopzCgEMSXjBc6AOMqYvWC1ktqTAfzJZUZgYf6w6lg=
|
||||
go.uber.org/goleak v1.3.0 h1:2K3zAYmnTNqV73imy9J1T3WC+gmCePx2hEGkimedGto=
|
||||
go.uber.org/goleak v1.3.0/go.mod h1:CoHD4mav9JJNrW/WLlf7HGZPjdw8EucARQHekz1X6bE=
|
||||
go.uber.org/multierr v1.10.0 h1:S0h4aNzvfcFsC3dRF1jLoaov7oRaKqRGC/pUEJ2yvPQ=
|
||||
go.uber.org/multierr v1.10.0/go.mod h1:20+QtiLqy0Nd6FdQB9TLXag12DsQkrbs3htMFfDN80Y=
|
||||
go.uber.org/zap v1.27.0 h1:aJMhYGrd5QSmlpLMr2MftRKl7t8J8PTZPA732ud/XR8=
|
||||
go.uber.org/zap v1.27.0/go.mod h1:GB2qFLM7cTU87MWRP2mPIjqfIDnGu+VIO4V/SdhGo2E=
|
||||
golang.org/x/arch v0.0.0-20210923205945-b76863e36670/go.mod h1:5om86z9Hs0C8fWVUuoMHwpExlXzs5Tkyp9hOrfG7pp8=
|
||||
golang.org/x/arch v0.8.0 h1:3wRIsP3pM4yUptoR96otTUOXI367OS0+c9eeRi9doIc=
|
||||
golang.org/x/arch v0.8.0/go.mod h1:FEVrYAQjsQXMVJ1nsMoVVXPZg6p2JE2mx8psSWTDQys=
|
||||
golang.org/x/crypto v0.21.0 h1:X31++rzVUdKhX5sWmSOFZxx8UW/ldWx55cbf08iNAMA=
|
||||
golang.org/x/crypto v0.21.0/go.mod h1:0BP7YvVV9gBbVKyeTG0Gyn+gZm94bibOW5BjDEYAOMs=
|
||||
golang.org/x/crypto v0.23.0 h1:dIJU/v2J8Mdglj/8rJ6UUOM3Zc9zLZxVZwwxMooUSAI=
|
||||
golang.org/x/crypto v0.23.0/go.mod h1:CKFgDieR+mRhux2Lsu27y0fO304Db0wZe70UKqHu0v8=
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9 h1:GoHiUyI/Tp2nVkLI2mCxVkOjsbSXD66ic0XW0js0R9g=
|
||||
golang.org/x/exp v0.0.0-20230905200255-921286631fa9/go.mod h1:S2oDrQGGwySpoQPVqRShND87VCbxmc6bL1Yd2oYrm6k=
|
||||
golang.org/x/net v0.25.0 h1:d/OCCoBEUq33pjydKrGQhw7IlUPI2Oylr+8qLx49kac=
|
||||
golang.org/x/net v0.25.0/go.mod h1:JkAGAh7GEvH74S6FOH42FLoXpXbE/aqXSrIQjXgsiwM=
|
||||
golang.org/x/sys v0.5.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.6.0/go.mod h1:oPkhp1MJrh7nUepCBck5+mAzfO9JrbApNNgaTdGDITg=
|
||||
golang.org/x/sys v0.20.0 h1:Od9JTbYCk261bKm4M/mw7AklTlFYIa0bIp9BgSm1S8Y=
|
||||
golang.org/x/sys v0.20.0/go.mod h1:/VUhepiaJMQUp4+oa/7Zr1D23ma6VTLIYjOOTFZPUcA=
|
||||
golang.org/x/text v0.15.0 h1:h1V/4gjBv8v9cjcR6+AR5+/cIYK5N/WAgiv4xlsEtAk=
|
||||
golang.org/x/text v0.15.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU=
|
||||
google.golang.org/protobuf v1.34.1 h1:9ddQBjfCyZPOHPUiPxpYESBLc+T8P3E+Vo4IbKZgFWg=
|
||||
google.golang.org/protobuf v1.34.1/go.mod h1:c6P6GXX6sHbq/GpV6MGZEdwhWPcYBgnhAHhKbcUYpos=
|
||||
gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0=
|
||||
gopkg.in/ini.v1 v1.67.0 h1:Dgnx+6+nfE+IfzjUEISNeydPJh9AXNNsWbGP9KzCsOA=
|
||||
gopkg.in/ini.v1 v1.67.0/go.mod h1:pNLf8WUiyNEtQjuu5G5vTm06TEv9tsIgeAvK8hOrP4k=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1 h1:bBRl1b0OH9s/DuPhuXpNl+VtCaJXFZ5/uEFST95x9zc=
|
||||
gopkg.in/natefinch/lumberjack.v2 v2.2.1/go.mod h1:YD8tP3GAjkrDg1eZH7EGmyESg/lsYskCTPBJVb9jqSc=
|
||||
gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA=
|
||||
gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM=
|
||||
gorm.io/driver/sqlite v1.5.6 h1:fO/X46qn5NUEEOZtnjJRWRzZMe8nqJiQ9E+0hi+hKQE=
|
||||
gorm.io/driver/sqlite v1.5.6/go.mod h1:U+J8craQU6Fzkcvu8oLeAQmi50TkwPEhHDEjQZXDah4=
|
||||
gorm.io/gorm v1.25.7 h1:VsD6acwRjz2zFxGO50gPO6AkNs7KKnvfzUjHQhZDz/A=
|
||||
gorm.io/gorm v1.25.7/go.mod h1:hbnx/Oo0ChWMn1BIhpy1oYozzpM15i4YPuHDmfYtwg8=
|
||||
nullprogram.com/x/optparse v1.0.0/go.mod h1:KdyPE+Igbe0jQUrVfMqDMeJQIJZEuyV7pjYmp6pbG50=
|
||||
rsc.io/pdf v0.1.1/go.mod h1:n8OzWcQ6Sp37PL01nO98y4iUCRdTGarVfzxY20ICaU4=
|
||||
159
Web开发/06go-auth-api/handlers.go
Normal file
159
Web开发/06go-auth-api/handlers.go
Normal file
@@ -0,0 +1,159 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// 注册用户
|
||||
func Register(cfg *Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req RegisterRequest
|
||||
err := c.ShouldBindJSON(&req)
|
||||
if err != nil {
|
||||
Logger.Error("参数错误", zap.Error(err))
|
||||
c.JSON(400, gin.H{
|
||||
"message": "参数错误",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 验证邮箱
|
||||
if EmailExists(req.Email) {
|
||||
c.JSON(400, gin.H{
|
||||
"message": "邮箱已存在",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
//密码加密
|
||||
hashedPassword, err := HashPassword(req.Password)
|
||||
if err != nil {
|
||||
Logger.Error("密码加密失败", zap.Error(err))
|
||||
c.JSON(500, gin.H{
|
||||
"message": "密码加密失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
// 创建用户
|
||||
user := User{
|
||||
Name: req.Name,
|
||||
Email: req.Email,
|
||||
Password: hashedPassword,
|
||||
Phone: req.Phone,
|
||||
}
|
||||
|
||||
err = DB.Create(&user).Error
|
||||
if err != nil {
|
||||
Logger.Error("创建用户失败", zap.Error(err))
|
||||
c.JSON(500, gin.H{
|
||||
"message": "创建用户失败",
|
||||
})
|
||||
return
|
||||
}
|
||||
|
||||
Logger.Info("用户注册成功", zap.String("email", req.Email))
|
||||
|
||||
c.JSON(200, gin.H{
|
||||
"message": "用户注册成功",
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 登录
|
||||
func Login(cfg *Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
var req LoginRequest
|
||||
|
||||
err := c.ShouldBindJSON(&req)
|
||||
if err != nil {
|
||||
c.JSON(400, gin.H{"错误": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
//查找用户
|
||||
var user User
|
||||
err = DB.Where("email = ?", req.Email).First(&user).Error
|
||||
if err != nil {
|
||||
Logger.Warn("用户不存在", zap.String("email", req.Email))
|
||||
c.JSON(401, gin.H{"错误": "电子邮件或密码无效"})
|
||||
return
|
||||
}
|
||||
|
||||
//验证密码
|
||||
if !VerifyPassword(user.Password, req.Password) {
|
||||
Logger.Warn("密码错误", zap.String("email", req.Email))
|
||||
c.JSON(401, gin.H{"错误": "电子邮件或密码无效"})
|
||||
return
|
||||
}
|
||||
|
||||
//生成token
|
||||
token, err := GenerateToken(user.ID, user.Email, cfg.JWT.Secret, int64(cfg.JWT.Expire))
|
||||
|
||||
if err != nil {
|
||||
Logger.Error("生成token失败", zap.Error(err))
|
||||
c.JSON(500, gin.H{"错误": "生成token失败"})
|
||||
return
|
||||
}
|
||||
|
||||
Logger.Info("用户登录成功", zap.String("email", req.Email))
|
||||
|
||||
c.JSON(200, LoginResponse{
|
||||
Token: token,
|
||||
User: User{
|
||||
ID: user.ID,
|
||||
Name: user.Name,
|
||||
Email: user.Email,
|
||||
Phone: user.Phone,
|
||||
Age: user.Age,
|
||||
},
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
// 获取用户信息
|
||||
func GetProfile(c *gin.Context) {
|
||||
userID, _ := c.Get("user_id")
|
||||
|
||||
var user User
|
||||
if err := DB.First(&user, userID.(uint)).Error; err != nil {
|
||||
c.JSON(404, gin.H{"error": "User not found"})
|
||||
return
|
||||
}
|
||||
|
||||
c.JSON(200, user)
|
||||
}
|
||||
|
||||
// 更新用户信息
|
||||
func UpdateProfile(c *gin.Context) {
|
||||
userID, _ := c.Get("user_id")
|
||||
|
||||
var req struct {
|
||||
Name string `json:"name"`
|
||||
Phone string `json:"phone"`
|
||||
Age int `json:"age"`
|
||||
}
|
||||
|
||||
if err := c.ShouldBindJSON(&req); err != nil {
|
||||
c.JSON(400, gin.H{"error": err.Error()})
|
||||
return
|
||||
}
|
||||
|
||||
if err := DB.Model(&User{}).Where("id = ?", userID.(uint)).Updates(req).Error; err != nil {
|
||||
Logger.Error("Failed to update user", zap.Error(err))
|
||||
c.JSON(500, gin.H{"error": "Failed to update profile"})
|
||||
return
|
||||
}
|
||||
|
||||
Logger.Info("User profile updated", zap.Uint("user_id", userID.(uint)))
|
||||
c.JSON(200, gin.H{"message": "Profile updated successfully"})
|
||||
}
|
||||
|
||||
// 健康检查
|
||||
func HealthCheck(c *gin.Context) {
|
||||
c.JSON(200, gin.H{
|
||||
"status": "ok",
|
||||
"app": "AuthAPI",
|
||||
})
|
||||
}
|
||||
66
Web开发/06go-auth-api/jwt.go
Normal file
66
Web开发/06go-auth-api/jwt.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/golang-jwt/jwt/v4"
|
||||
)
|
||||
|
||||
type Claims struct {
|
||||
UserID uint `json:"user_id"`
|
||||
Email string `json:"email"`
|
||||
jwt.RegisteredClaims
|
||||
}
|
||||
|
||||
func GenerateToken(userID uint, email string, secret string, expire int64) (string, error) {
|
||||
claims := Claims{
|
||||
UserID: userID,
|
||||
Email: email,
|
||||
RegisteredClaims: jwt.RegisteredClaims{
|
||||
ExpiresAt: jwt.NewNumericDate(time.Now().Add(time.Duration(expire) * time.Second)),
|
||||
IssuedAt: jwt.NewNumericDate(time.Now()),
|
||||
},
|
||||
}
|
||||
token := jwt.NewWithClaims(jwt.SigningMethodHS256, claims)
|
||||
tokenString, err := token.SignedString([]byte(secret))
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return tokenString, nil
|
||||
}
|
||||
|
||||
// VerifyToken 验证JWT令牌的有效性
|
||||
// 参数:
|
||||
//
|
||||
// tokenString - JWT令牌字符串
|
||||
// secret - 用于验证令牌的密钥
|
||||
//
|
||||
// 返回值:
|
||||
//
|
||||
// *Claims - 解析出的令牌声明信息
|
||||
// error - 验证过程中出现的错误
|
||||
func VerifyToken(tokenString string, secret string) (*Claims, error) {
|
||||
claims := &Claims{}
|
||||
token, err := jwt.ParseWithClaims(tokenString, claims, func(token *jwt.Token) (interface{}, error) {
|
||||
|
||||
// 检查签名方法是否为HMAC
|
||||
if _, ok := token.Method.(*jwt.SigningMethodHMAC); !ok {
|
||||
return nil, fmt.Errorf("unexpected signing method: %v", token.Header["alg"])
|
||||
}
|
||||
return []byte(secret), nil
|
||||
})
|
||||
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
|
||||
// 验证令牌是否有效
|
||||
if !token.Valid {
|
||||
return nil, fmt.Errorf("invalid token")
|
||||
}
|
||||
|
||||
return claims, nil
|
||||
|
||||
}
|
||||
56
Web开发/06go-auth-api/logger.go
Normal file
56
Web开发/06go-auth-api/logger.go
Normal file
@@ -0,0 +1,56 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"os"
|
||||
|
||||
"go.uber.org/zap"
|
||||
"go.uber.org/zap/zapcore"
|
||||
"gopkg.in/natefinch/lumberjack.v2"
|
||||
)
|
||||
|
||||
var Logger *zap.Logger
|
||||
|
||||
func InitLogger(env string) error {
|
||||
var level zapcore.Level
|
||||
|
||||
switch env {
|
||||
case "prod":
|
||||
level = zapcore.WarnLevel
|
||||
case "test":
|
||||
level = zapcore.DebugLevel
|
||||
default:
|
||||
level = zapcore.InfoLevel
|
||||
}
|
||||
|
||||
logfile := &lumberjack.Logger{
|
||||
Filename: "logs/app.log",
|
||||
MaxSize: 100,
|
||||
MaxBackups: 10,
|
||||
MaxAge: 30,
|
||||
Compress: true,
|
||||
}
|
||||
|
||||
encoderConfig := zapcore.EncoderConfig{
|
||||
TimeKey: "ts",
|
||||
LevelKey: "level",
|
||||
MessageKey: "msg",
|
||||
CallerKey: "caller",
|
||||
EncodeLevel: zapcore.LowercaseLevelEncoder,
|
||||
EncodeTime: zapcore.ISO8601TimeEncoder,
|
||||
EncodeCaller: zapcore.ShortCallerEncoder,
|
||||
}
|
||||
|
||||
core := zapcore.NewCore(
|
||||
zapcore.NewJSONEncoder(encoderConfig),
|
||||
zapcore.NewMultiWriteSyncer(
|
||||
zapcore.AddSync(os.Stdout),
|
||||
zapcore.AddSync(logfile),
|
||||
),
|
||||
level,
|
||||
)
|
||||
|
||||
Logger = zap.New(core, zap.AddCaller())
|
||||
zap.ReplaceGlobals(Logger)
|
||||
|
||||
return nil
|
||||
}
|
||||
24
Web开发/06go-auth-api/logs/app.log
Normal file
24
Web开发/06go-auth-api/logs/app.log
Normal file
@@ -0,0 +1,24 @@
|
||||
{"level":"info","ts":"2025-12-30T17:50:54.962+0800","caller":"06go-auth-api/db.go:30","msg":"数据库初始化成功"}
|
||||
{"level":"info","ts":"2025-12-30T17:50:54.962+0800","caller":"06go-auth-api/main.go:57","msg":"Server starting","app":"AuthAPI","port":8080,"env":"dev"}
|
||||
{"level":"fatal","ts":"2025-12-30T17:50:54.963+0800","caller":"06go-auth-api/main.go:64","msg":"Server error","error":"listen tcp :8080: bind: address already in use"}
|
||||
{"level":"info","ts":"2025-12-30T17:52:46.052+0800","caller":"06go-auth-api/db.go:30","msg":"数据库初始化成功"}
|
||||
{"level":"info","ts":"2025-12-30T17:52:46.052+0800","caller":"06go-auth-api/main.go:57","msg":"Server starting","app":"AuthAPI","port":8088,"env":"dev"}
|
||||
{"level":"info","ts":"2025-12-30T17:53:51.134+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"POST","路径":"/api/register","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:53:51.210+0800","caller":"06go-auth-api/handlers.go:56","msg":"用户注册成功","email":"alice@example.com"}
|
||||
{"level":"info","ts":"2025-12-30T17:53:51.210+0800","caller":"06go-auth-api/middleware.go:26","msg":"响应","路径":"/api/register","状态码":200}
|
||||
{"level":"info","ts":"2025-12-30T17:54:17.482+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"POST","路径":"/api/login","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:54:17.532+0800","caller":"06go-auth-api/handlers.go:100","msg":"用户登录成功","email":"alice@example.com"}
|
||||
{"level":"info","ts":"2025-12-30T17:54:17.532+0800","caller":"06go-auth-api/middleware.go:26","msg":"响应","路径":"/api/login","状态码":200}
|
||||
{"level":"info","ts":"2025-12-30T17:54:53.342+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:55:00.113+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:55:11.577+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:56:24.245+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:56:56.927+0800","caller":"06go-auth-api/db.go:30","msg":"数据库初始化成功"}
|
||||
{"level":"info","ts":"2025-12-30T17:56:56.927+0800","caller":"06go-auth-api/main.go:57","msg":"Server starting","app":"AuthAPI","port":8088,"env":"dev"}
|
||||
{"level":"info","ts":"2025-12-30T17:57:06.731+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:58:16.750+0800","caller":"06go-auth-api/db.go:30","msg":"数据库初始化成功"}
|
||||
{"level":"info","ts":"2025-12-30T17:58:16.750+0800","caller":"06go-auth-api/main.go:57","msg":"Server starting","app":"AuthAPI","port":8088,"env":"dev"}
|
||||
{"level":"info","ts":"2025-12-30T17:58:23.713+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:58:23.714+0800","caller":"06go-auth-api/middleware.go:26","msg":"响应","路径":"/api/profile","状态码":200}
|
||||
{"level":"info","ts":"2025-12-30T17:58:57.676+0800","caller":"06go-auth-api/middleware.go:17","msg":"请求","方法":"GET","路径":"/api/profile","IP":"::1"}
|
||||
{"level":"info","ts":"2025-12-30T17:58:57.676+0800","caller":"06go-auth-api/middleware.go:26","msg":"响应","路径":"/api/profile","状态码":401}
|
||||
66
Web开发/06go-auth-api/main.go
Normal file
66
Web开发/06go-auth-api/main.go
Normal file
@@ -0,0 +1,66 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
func main() {
|
||||
|
||||
//加载配置
|
||||
cfg, err := LoadConfig()
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
//初始化日志
|
||||
err = InitLogger(cfg.App.Env)
|
||||
if err != nil {
|
||||
panic(err)
|
||||
}
|
||||
|
||||
defer Logger.Sync()
|
||||
|
||||
//初始化数据库
|
||||
err = InitDB(cfg)
|
||||
if err != nil {
|
||||
Logger.Fatal("数据库初始化失败", zap.Error(err))
|
||||
}
|
||||
|
||||
//创建Gin应用
|
||||
r := gin.Default()
|
||||
|
||||
//中间件
|
||||
r.Use(LoggingMiddleware())
|
||||
r.Use(CORSMiddleware())
|
||||
|
||||
// 公开路由
|
||||
public := r.Group("/api")
|
||||
{
|
||||
public.GET("/health", HealthCheck)
|
||||
public.POST("/register", Register(cfg))
|
||||
public.POST("/login", Login(cfg))
|
||||
}
|
||||
|
||||
// 受保护的路由
|
||||
protected := r.Group("/api")
|
||||
protected.Use(AuthMiddleware(cfg))
|
||||
{
|
||||
protected.GET("/profile", GetProfile)
|
||||
protected.PUT("/profile", UpdateProfile)
|
||||
}
|
||||
|
||||
// 启动服务器
|
||||
addr := fmt.Sprintf(":%d", cfg.App.Port)
|
||||
Logger.Info("Server starting",
|
||||
zap.String("app", cfg.App.Name),
|
||||
zap.Int("port", cfg.App.Port),
|
||||
zap.String("env", cfg.App.Env),
|
||||
)
|
||||
|
||||
if err = r.Run(addr); err != nil {
|
||||
Logger.Fatal("Server error", zap.Error(err))
|
||||
}
|
||||
}
|
||||
94
Web开发/06go-auth-api/middleware.go
Normal file
94
Web开发/06go-auth-api/middleware.go
Normal file
@@ -0,0 +1,94 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"strings"
|
||||
|
||||
"github.com/gin-gonic/gin"
|
||||
"go.uber.org/zap"
|
||||
)
|
||||
|
||||
// LoggingMiddleware 创建一个请求日志中间件
|
||||
// 该中间件会在每个HTTP请求进入时记录请求信息,在响应返回时记录响应信息
|
||||
// 参数: 无
|
||||
// 返回值: gin.HandlerFunc - Gin框架的中间件处理函数
|
||||
func LoggingMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 记录请求日志:方法、路径、客户端IP
|
||||
Logger.Info("请求",
|
||||
zap.String("方法", c.Request.Method),
|
||||
zap.String("路径", c.Request.URL.Path),
|
||||
zap.String("IP", c.ClientIP()),
|
||||
)
|
||||
|
||||
c.Next()
|
||||
|
||||
// 记录响应日志:路径、状态码
|
||||
Logger.Info("响应",
|
||||
zap.String("路径", c.Request.URL.Path),
|
||||
zap.Int("状态码", c.Writer.Status()),
|
||||
)
|
||||
}
|
||||
}
|
||||
|
||||
// AuthMiddleware JWT 认证中间件
|
||||
// 参数: cfg - 配置对象,包含JWT密钥等配置信息
|
||||
// 返回值: gin.HandlerFunc - Gin框架的中间件处理函数
|
||||
func AuthMiddleware(cfg *Config) gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
authHeader := c.GetHeader("Authorization")
|
||||
|
||||
if authHeader == "" {
|
||||
c.JSON(401, gin.H{"错误": "错误的认证头"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 解析Authorization头,验证格式为 "Bearer <token>"
|
||||
parts := strings.SplitN(authHeader, " ", 2)
|
||||
if len(parts) != 2 || parts[0] != "Bearer" {
|
||||
c.JSON(401, gin.H{"错误": "错误的认证头"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 验证JWT token的有效性
|
||||
claims, err := VerifyToken(parts[1], cfg.JWT.Secret)
|
||||
if err != nil {
|
||||
Logger.Error("验证token失败", zap.Error(err))
|
||||
c.JSON(401, gin.H{"错误": "验证token失败"})
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
|
||||
// 将用户信息保存到上下文
|
||||
c.Set("user_id", claims.UserID)
|
||||
c.Set("email", claims.Email)
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
|
||||
// CORSMiddleware 创建并返回一个CORS(跨域资源共享)中间件处理器
|
||||
// 该中间件用于处理跨域请求,设置相应的响应头信息
|
||||
//
|
||||
// 参数:
|
||||
//
|
||||
// 无
|
||||
//
|
||||
// 返回值:
|
||||
//
|
||||
// gin.HandlerFunc - Gin框架的中间件处理器函数
|
||||
func CORSMiddleware() gin.HandlerFunc {
|
||||
return func(c *gin.Context) {
|
||||
// 设置CORS相关响应头
|
||||
c.Writer.Header().Set("Access-Control-Allow-Origin", "*")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, DELETE, OPTIONS")
|
||||
c.Writer.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization")
|
||||
|
||||
// 处理预检请求(OPTIONS方法)
|
||||
if c.Request.Method == "OPTIONS" {
|
||||
c.AbortWithStatus(204)
|
||||
return
|
||||
}
|
||||
c.Next()
|
||||
}
|
||||
}
|
||||
42
Web开发/06go-auth-api/models.go
Normal file
42
Web开发/06go-auth-api/models.go
Normal file
@@ -0,0 +1,42 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"gorm.io/gorm"
|
||||
)
|
||||
|
||||
type User struct {
|
||||
ID uint `gorm:"primaryKey" json:"id"`
|
||||
Name string `gorm:"size:100;not null" json:"name"`
|
||||
Email string `gorm:"size:100;unique;not null" json:"email"`
|
||||
Password string `gorm:"size:255;not null" json:"-"` // 不在 JSON 中显示
|
||||
Phone string `gorm:"size:20" json:"phone,omitempty"`
|
||||
Age int `json:"age,omitempty"`
|
||||
Active bool `gorm:"default:true" json:"active"`
|
||||
CreatedAt time.Time `json:"created_at"`
|
||||
UpdatedAt time.Time `json:"updated_at"`
|
||||
DeletedAt gorm.DeletedAt `json:"-"`
|
||||
}
|
||||
|
||||
func (User) TableName() string {
|
||||
return "users"
|
||||
}
|
||||
|
||||
// 请求体
|
||||
type RegisterRequest struct {
|
||||
Name string `json:"name" binding:"required"`
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required,min=6"`
|
||||
Phone string `json:"phone" binding:"omitempty,len=11"`
|
||||
}
|
||||
|
||||
type LoginRequest struct {
|
||||
Email string `json:"email" binding:"required,email"`
|
||||
Password string `json:"password" binding:"required"`
|
||||
}
|
||||
|
||||
type LoginResponse struct {
|
||||
Token string `json:"token"`
|
||||
User User `json:"user"`
|
||||
}
|
||||
28
Web开发/06go-auth-api/utils.go
Normal file
28
Web开发/06go-auth-api/utils.go
Normal file
@@ -0,0 +1,28 @@
|
||||
package main
|
||||
|
||||
import (
|
||||
"golang.org/x/crypto/bcrypt"
|
||||
)
|
||||
|
||||
// 密码加密
|
||||
func HashPassword(password string) (string, error) {
|
||||
hash, err := bcrypt.GenerateFromPassword([]byte(password), 10)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
|
||||
return string(hash), nil
|
||||
}
|
||||
|
||||
// 密码验证
|
||||
func VerifyPassword(hashedPassword, password string) bool {
|
||||
err := bcrypt.CompareHashAndPassword([]byte(hashedPassword), []byte(password))
|
||||
return err == nil
|
||||
}
|
||||
|
||||
// 检查邮箱是否注册
|
||||
func EmailExists(email string) bool {
|
||||
var count int64
|
||||
DB.Model(&User{}).Where("email = ?", email).Count(&count)
|
||||
return count > 0
|
||||
}
|
||||
Reference in New Issue
Block a user