diff --git a/scripts/main.go b/scripts/main.go new file mode 100644 index 0000000..7a25b0c --- /dev/null +++ b/scripts/main.go @@ -0,0 +1,85 @@ +package main + +import ( + "bufio" + "encoding/json" + "fmt" + "io/ioutil" + "net/http" + "os" + "os/exec" +) + +type Message struct { + Message string `json:"message"` + From string `json:"from"` + To string `json:"to"` +} + +func handleRequest(w http.ResponseWriter, r *http.Request) { + // Read the request body + body, err := ioutil.ReadAll(r.Body) + if err != nil { + http.Error(w, "Error reading request body: "+err.Error(), http.StatusInternalServerError) + return + } + defer r.Body.Close() + + // Unmarshal the JSON data + var msg Message + err = json.Unmarshal(body, &msg) + if err != nil { + http.Error(w, "Error unmarshalling JSON: "+err.Error(), http.StatusBadRequest) + return + } + + // Check if From and To fields are not longer than 2 letters + if len(msg.From) > 2 || len(msg.To) > 2 { + http.Error(w, "From and To fields should not be longer than 2 letters.", http.StatusBadRequest) + return + } + + // Start the Python command in the background + cmd := exec.Command("python", "scripts/python/main.py", msg.Message, msg.From, msg.To) + output, err := cmd.StdoutPipe() + if err != nil { + http.Error(w, "Error starting Python command: "+err.Error(), http.StatusInternalServerError) + return + } + err = cmd.Start() + if err != nil { + http.Error(w, "Error starting Python command: "+err.Error(), http.StatusInternalServerError) + return + } + + // Read the output of the Python command and send it to the client + scanner := bufio.NewScanner(output) + for scanner.Scan() { + fmt.Fprintln(w, scanner.Text()) + } + + // Wait for the command to complete + err = cmd.Wait() + if err != nil { + http.Error(w, "Error waiting for Python command: "+err.Error(), http.StatusInternalServerError) + return + } +} + +func main() { + // Define the HTTP handler function + http.HandleFunc("/api", handleRequest) + + // Get the port number from the environment variable or use a default value + port := "11435" + if p := os.Getenv("PORT"); p != "" { + port = p + } + + // Start the HTTP server + fmt.Printf("Listening on :%s...\n", port) + err := http.ListenAndServe(":"+port, nil) + if err != nil { + panic(err) + } +}