-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
86 lines (73 loc) · 1.97 KB
/
main.go
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
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"time"
"block-scanner/config"
"block-scanner/internal/blockchain"
"block-scanner/internal/database"
"block-scanner/internal/queue"
)
func main() {
// 加载配置
cfg, err := config.LoadConfig("config/config.yaml")
if err != nil {
log.Fatalf("Error loading config: %v", err)
}
// 初始化数据库连接
err = database.InitDB(cfg)
if err != nil {
log.Fatalf("Error initializing database: %v", err)
}
defer database.CloseDB()
// 初始化 RabbitMQ 连接
err = queue.InitRabbitMQ(cfg)
if err != nil {
log.Fatalf("Error initializing RabbitMQ: %v", err)
}
defer queue.CloseRabbitMQ()
// 创建并启动扫描器
scanner, err := blockchain.NewScanner(cfg)
if err != nil {
log.Fatalf("Error creating scanner: %v", err)
}
// 在后台启动扫描器
go func() {
if err := scanner.Start(); err != nil {
log.Fatalf("Error starting scanner: %v", err)
}
}()
// 设置一个简单的 HTTP 服务器,用于健康检查
http.HandleFunc("/health", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
fmt.Fprintf(w, "Scanner is running")
})
// 创建 HTTP 服务器
server := &http.Server{
Addr: fmt.Sprintf(":%d", cfg.Server.Port),
Handler: http.DefaultServeMux,
}
// 在后台启动 HTTP 服务器
go func() {
log.Printf("Starting server on %s", server.Addr)
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Error starting server: %v", err)
}
}()
// 等待中断信号以优雅地关闭服务器(设置 5 秒的超时时间)
quit := make(chan os.Signal, 1)
signal.Notify(quit, syscall.SIGINT, syscall.SIGTERM)
<-quit
log.Println("Shutting down server...")
ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second)
defer cancel()
if err := server.Shutdown(ctx); err != nil {
log.Fatalf("Server forced to shutdown: %v", err)
}
log.Println("Server exiting")
}