-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
89 lines (77 loc) · 1.84 KB
/
main.go
File metadata and controls
89 lines (77 loc) · 1.84 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
package main
import (
"context"
"log"
"net/http"
"api_qps_go/config"
"api_qps_go/models"
"time"
"github.com/gin-gonic/gin"
"go.mongodb.org/mongo-driver/mongo"
"go.mongodb.org/mongo-driver/mongo/options"
)
func main() {
// 初始化MongoDB连接
ctx := context.Background()
clientOptions := options.Client().
ApplyURI(config.MongoURI).
SetConnectTimeout(10 * time.Second)
mongoDB, err := mongo.Connect(ctx, clientOptions)
if err != nil {
log.Fatal("MongoDB连接失败:", err)
}
defer mongoDB.Disconnect(ctx)
// 测试MongoDB连接
if err := mongoDB.Ping(ctx, nil); err != nil {
log.Fatal("MongoDB ping失败:", err)
}
log.Println("MongoDB连接成功")
// 创建IP限流器
limiter := models.NewIPLimiter()
// 初始化Gin路由
r := gin.Default()
// 添加IP限流中间件
r.Use(func(c *gin.Context) {
ip := c.ClientIP()
if err := limiter.CheckIPLimit(c.Request.Context(), ip); err != nil {
c.JSON(http.StatusTooManyRequests, gin.H{"error": err.Error()})
c.Abort()
return
}
c.Next()
})
// 根路由 - API说明
r.GET("/", func(c *gin.Context) {
c.JSON(http.StatusOK, gin.H{
"apis": []gin.H{
{
"path": "/random",
"method": "GET",
"description": "获取随机数据",
"params": gin.H{
"type": gin.H{
"required": false,
"description": "数据类型",
"options": config.TypeMap,
},
},
"about": "https://home.lideshan.top",
},
},
})
})
// 定义API路由
r.GET("/random", func(c *gin.Context) {
typeParam := c.Query("type")
data, err := models.GetRandomData(c.Request.Context(), mongoDB, typeParam)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{"error": err.Error()})
return
}
c.JSON(http.StatusOK, data)
})
// 启动服务器
if err := r.Run(":8080"); err != nil {
log.Fatal(err)
}
}