带有 Google OAuth2 的 Fiber
此示例演示了如何在 Fiber 应用中实现 Google OAuth2 认证。
先决条件
- Go 1.16 或更高版本
- Go 模块
设置
-
克隆仓库
git clone https://github.com/gofiber/recipes.git
cd recipes/oauth2-google -
安装依赖项
go mod tidy
-
从 Google Developers Console 获取 OAuth 凭据。
-
在根目录中创建
.env
文件并添加您的 Google OAuth 凭据APP_PORT=3300
GOOGLE_CLIENT_ID=your_client_id
GOOGLE_CLIENT_SECRET=your_client_secret
GOOGLE_REDIRECT_URL=http://localhost:3300/api/auth/google/callback
运行应用
-
运行应用
go run main.go
-
服务器将在
http://localhost:3300
启动。
端点
方法 | URL | 描述 |
---|---|---|
GET | /api/ | 重定向到 Google 登录 URL |
GET | /api/auth/google/callback | 处理 Google OAuth2 回调并返回用户电子邮件 |
示例请求
重定向到 Google 登录
curl -X GET http://localhost:3300/api/
Google OAuth2 回调
curl -X GET http://localhost:3300/api/auth/google/callback?state=state&code=code