-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathformatter.go
81 lines (70 loc) · 2.51 KB
/
formatter.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
package main
import (
"encoding/json"
"log"
"github.com/gofiber/contrib/websocket"
)
type FormatResponse struct {
Success bool
Data string
}
func fileFormatterController() func(c *websocket.Conn) {
return func(c *websocket.Conn) {
log.Println(c.RemoteAddr(), "Connection opened for format request!")
c.SetCloseHandler(func(code int, text string) error {
log.Printf("WebSocket connection for format closed with code %d and text: %s", code, text)
return nil
})
for {
mt, msg, err := c.ReadMessage()
if mt == websocket.CloseMessage|websocket.CloseGoingAway|websocket.CloseAbnormalClosure {
log.Println(c.RemoteAddr(), "Closing formatter websocket")
return
}
log.Println(c.RemoteAddr(), "Received format request!")
if err != nil {
logAndSendFormatErrorToClient(c, mt, "Format controller :: Error in Reading message from websocket:", err)
return
}
input, err := base64Decoder(string(msg))
if err != nil {
logAndSendFormatErrorToClient(c, mt, "Format controller :: Error in decoding input base64 code:", err)
continue
}
result, err := runFormatter(string(input))
if err != nil {
logAndSendFormatErrorToClient(c, mt, "Format controller :: Error in formatting input code:", err)
continue
}
response := FormatResponse{
Success: true,
Data: base64Encoder(string(result)),
}
responseJSON, err := json.Marshal(response)
if err != nil {
logAndSendFormatErrorToClient(c, mt, "Format controller :: Error in marshaling response:", err)
continue
}
base64EncodedResponse := base64Encoder(string(responseJSON))
if err = c.WriteMessage(mt, []byte(base64EncodedResponse)); err != nil {
logAndSendFormatErrorToClient(c, mt, "Format controller :: Error in writing back to the client:", err)
continue
}
log.Println(c.RemoteAddr(), "Sent format response!")
}
}
}
func logAndSendFormatErrorToClient(c *websocket.Conn, mt int, appErrorMessage string, sysError error) {
response := FormatResponse{
Success: false,
Data: appErrorMessage + sysError.Error(),
}
log.Println(c.RemoteAddr(), appErrorMessage, sysError.Error())
responseJSON, err := json.Marshal(response)
if err != nil {
log.Println(c.RemoteAddr(), "For ", appErrorMessage, " due to: ", sysError.Error(), "couldn't marshal response JSON due to: ", err.Error())
}
if err := c.WriteMessage(mt, responseJSON); err != nil {
log.Println(c.RemoteAddr(), "For ", appErrorMessage, " due to: ", sysError.Error(), "couldn't write back to client: ", err.Error())
}
}