diff --git a/main.go b/main.go index ce91bd1..d9ad936 100644 --- a/main.go +++ b/main.go @@ -30,12 +30,30 @@ type StreamResponse struct { const linux = "python3" func createStreamResponse(fromLanguage, toLanguage, message string) string { + var extractedMessage string + + // Try to unmarshal the message to see if it's a JSON object + var temp map[string]interface{} + if err := json.Unmarshal([]byte(message), &temp); err == nil { + // Check if the response field exists in the JSON object + if response, exists := temp["response"]; exists { + extractedMessage = fmt.Sprintf("%v", response) + } else { + // If no response field, use the entire message as a fallback + extractedMessage = message + } + } else { + // If unmarshalling fails, use the message as it is + extractedMessage = message + } + response := StreamResponse{ From: fromLanguage, To: toLanguage, CreatedAt: time.Now().Format(time.RFC3339), - Response: message, + Response: extractedMessage, } + jsonResp, err := json.Marshal(response) if err != nil { return `{"response": "Error in preparing the message."}` @@ -110,7 +128,8 @@ func executeTranslator(w http.ResponseWriter, message, fromLanguage, toLanguage messages := make(chan string) defer close(messages) - go streamResponse(w, fromLanguage, toLanguage, messages) + go streamResponse(w, messages) + cmd := exec.Command(linux, "translator/translate.py", message, fromLanguage, toLanguage) output, err := cmd.StdoutPipe() if err != nil { @@ -126,7 +145,8 @@ func executeTranslator(w http.ResponseWriter, message, fromLanguage, toLanguage scanner := bufio.NewScanner(output) for scanner.Scan() { - messages <- string(scanner.Bytes()) + // Directly send the translated text as a message + messages <- scanner.Text() } err = cmd.Wait()