-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathmain.go
More file actions
137 lines (111 loc) · 3.2 KB
/
main.go
File metadata and controls
137 lines (111 loc) · 3.2 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
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
package main
import (
"context"
"fmt"
"log"
"net/http"
"os"
"os/signal"
"syscall"
"github.com/gorilla/websocket"
"github.com/redis/go-redis/v9"
"gorm.io/driver/mysql"
"gorm.io/gorm"
)
// Global variables
var ctx = context.Background()
var rdb *redis.Client
var db *gorm.DB
var upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
type Message struct {
ID uint `gorm:"primaryKey"`
Channel string `gorm:"index"`
Content string
Timestamp int64 `gorm:"autoCreateTime"`
}
func init() {
var err error
rdb = redis.NewClient(&redis.Options{
Addr: "localhost:6379",
Password: "",
DB: 0,
})
dsn := "nora:root@tcp(localhost:3306)/chatdb?charset=utf8mb4&parseTime=True&loc=Local"
db, err = gorm.Open(mysql.Open(dsn), &gorm.Config{})
if err != nil {
log.Fatalf("Error connecting to MySQL: %v", err)
}
if err := db.AutoMigrate(&Message{}); err != nil {
log.Fatalf("Error migrating database: %v", err)
}
}
func storeMessage(channel, content string) error {
message := Message{Channel: channel, Content: content}
return db.Create(&message).Error
}
func PublishHandler(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
http.Error(w, "Method not allowed", http.StatusMethodNotAllowed)
return
}
channel := r.FormValue("channel")
message := r.FormValue("message")
if channel == "" || message == "" {
http.Error(w, "Channel and message are required", http.StatusBadRequest)
return
}
err := rdb.Publish(ctx, channel, message).Err()
if err != nil {
http.Error(w, "Error publishing message", http.StatusInternalServerError)
return
}
err = storeMessage(channel, message)
if err != nil {
http.Error(w, "Error storing message", http.StatusInternalServerError)
return
}
fmt.Fprintf(w, "Message published and stored in Mysql: %s", message)
}
func subscribeHandler(w http.ResponseWriter, r *http.Request) {
channels := r.URL.Query()["channel"] // Get multiple channel parameters
if len(channels) == 0 {
http.Error(w, "At least one 'channel' parameter is required", http.StatusBadRequest)
return
}
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
http.Error(w, "Failed to upgrade to WebSocket", http.StatusInternalServerError)
return
}
defer conn.Close()
pubsub := rdb.Subscribe(ctx, channels...) // Subscribe to multiple channels
defer pubsub.Close()
fmt.Printf("Client subscribed to channels: %v\n", channels)
ch := pubsub.Channel()
for msg := range ch {
if err := conn.WriteMessage(websocket.TextMessage, []byte(fmt.Sprintf("[%s] %s", msg.Channel, msg.Payload))); err != nil {
fmt.Printf("WebSocket error: %v\n", err)
break
}
}
}
func main() {
signalChan := make(chan os.Signal, 1)
signal.Notify(signalChan, os.Interrupt, syscall.SIGTERM)
http.HandleFunc("/publish", PublishHandler)
http.HandleFunc("/subscribe", subscribeHandler)
server := &http.Server{Addr: ":8080"}
go func() {
fmt.Println("Starting server on :8080")
if err := server.ListenAndServe(); err != nil && err != http.ErrServerClosed {
log.Fatalf("Server error: %v", err)
}
}()
<-signalChan
fmt.Println("Shutting down server...")
server.Close()
rdb.Close()
fmt.Println("Server shutdown complete")
}