reso-execution/main.go
2024-03-16 06:41:03 -07:00

58 lines
1.3 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"os"
"strings"
"github.com/gorilla/websocket"
)
const (
WS_HOST = "0.0.0.0"
WS_PORT = 5000
)
var Upgrader = websocket.Upgrader{
CheckOrigin: func(r *http.Request) bool { return true },
}
func main() {
http.HandleFunc("/", HandleWs)
// if ./workspace/ directory does not exist, create it
if _, err := os.Stat("./workspace/"); os.IsNotExist(err) {
os.Mkdir("./workspace/", 0755)
}
addr := fmt.Sprintf("%s:%d", WS_HOST, WS_PORT)
log.Println("Server started at", addr)
log.Fatal(http.ListenAndServe(addr, nil))
}
func HandleWs(w http.ResponseWriter, r *http.Request) {
c, err := Upgrader.Upgrade(w, r, nil)
if err != nil {
log.Print("upgrade:", err)
return
}
defer c.Close()
for {
// get the first line of the message from the client
_, message, err := c.ReadMessage()
if err != nil {
log.Println("read:", err)
break
}
// print the message to the console
log.Printf("recv: %s", message)
// seperate message into chunks by newline
msg := strings.Split(string(message), "\n")
sendMessage := handleCase(msg[0], strings.Join(msg[1:], "\n"))
// send the message back to the client
err = c.WriteMessage(websocket.TextMessage, []byte(sendMessage.String()))
}
}