Translator-GO-Endpoint/scripts/main.go

104 lines
2.5 KiB
Go

package main
import (
"bufio"
"bytes"
"encoding/json"
"fmt"
"io"
"log"
"net/http"
"os"
"os/exec"
)
type Message struct {
Message string `json:"message"`
From string `json:"from"`
To string `json:"to"`
}
func getAllPackages() {
TurnOn := exec.Command("python", "scripts/python/package_mangement/note_all_packages.py")
// Create a buffer to capture the standard output.
var out bytes.Buffer
TurnOn.Stdout = &out
// Execute the command.
err := TurnOn.Run()
if err != nil {
log.Fatal(err)
}
// Retrieve and print the standard output from the command.
fmt.Println("Output:", out.String())
}
func handleRequest(w http.ResponseWriter, r *http.Request) {
// Read the request body
body, err := io.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() {
getAllPackages()
// 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)
}
}