-
Notifications
You must be signed in to change notification settings - Fork 0
/
main.go
106 lines (85 loc) · 1.9 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
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"sync"
"github.com/gorilla/websocket"
"gopkg.in/yaml.v2"
)
var upgrader = websocket.Upgrader{
ReadBufferSize: 1024,
WriteBufferSize: 1024,
}
type Config struct {
Responses map[string]string `yaml:"responses"`
}
func readConfigFromFile(filePath string) (*Config, error) {
data, err := os.ReadFile(filePath)
if err != nil {
return nil, err
}
var config Config
err = yaml.Unmarshal(data, &config)
if err != nil {
return nil, err
}
return &config, nil
}
func Check(f func() error) {
if err := f(); err != nil {
fmt.Println("Received error:", err)
}
}
func handleWebSocket(w http.ResponseWriter, r *http.Request, config *Config) {
conn, err := upgrader.Upgrade(w, r, nil)
if err != nil {
log.Println(err)
return
}
defer Check(conn.Close)
fmt.Println("Client Connected")
for {
messageType, p, err := conn.ReadMessage()
if err != nil {
log.Println(err)
return
}
clientMessage := strings.TrimSuffix(string(p), "\n")
fmt.Printf("Received message: %s\n", clientMessage)
response, exists := config.Responses[clientMessage]
if !exists {
response = "No response found for the given message."
}
err = conn.WriteMessage(messageType, []byte(response))
if err != nil {
log.Println(err)
return
}
}
}
func main() {
port := "8080"
filePath := "responses.yaml"
config, err := readConfigFromFile(filePath)
if err != nil {
log.Fatal("Error reading config from file:", err)
}
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
http.HandleFunc("/ws", func(w http.ResponseWriter, r *http.Request) {
handleWebSocket(w, r, config)
})
fmt.Printf("Server is listening on :%s\n", port)
err := http.ListenAndServe(":"+port, nil)
if err != nil {
log.Fatal("ListenAndServe: ", err)
}
}()
// Wait for the goroutine to finish (this will never happen unless there's an error)
wg.Wait()
}