This commit is contained in:
Falko Victor Habel 2024-07-29 17:50:31 +02:00
parent 34075e6da5
commit 6a73f0ed9e
1 changed files with 14 additions and 12 deletions

26
main.go
View File

@ -22,26 +22,28 @@ type Message struct {
const linux = "python3" const linux = "python3"
func extractMessage(message string) (string, error) { func streamResponse(w http.ResponseWriter, messages <-chan string) {
var temp map[string]interface{} w.Header().Set("Content-Type", "text/plain; charset=utf-8")
err := json.Unmarshal([]byte(message), &temp) w.Header().Set("Cache-Control", "no-cache")
if err != nil { w.Header().Set("Connection", "keep-alive")
return "", fmt.Errorf("failed to unmarshal message: %v", err)
flusher, ok := w.(http.Flusher)
if !ok {
http.Error(w, "Streaming unsupported!", http.StatusInternalServerError)
return
} }
response, exists := temp["response"] for msg := range messages {
if !exists { fmt.Fprintf(w, "%s\n", msg)
return "", fmt.Errorf("no 'response' field found in the message") flusher.Flush()
} }
return fmt.Sprintf("%v", response), nil
} }
func downloadPackages(w http.ResponseWriter, fromLanguage, toLanguage string) { func downloadPackages(w http.ResponseWriter, fromLanguage, toLanguage string) {
messages := make(chan string) messages := make(chan string)
defer close(messages) defer close(messages)
go extractMessage(messages) go streamResponse(w, messages)
cmd := exec.Command(linux, "translator/download.py", fromLanguage, toLanguage) cmd := exec.Command(linux, "translator/download.py", fromLanguage, toLanguage)
output, err := cmd.StdoutPipe() output, err := cmd.StdoutPipe()
@ -86,7 +88,7 @@ func executeTranslator(w http.ResponseWriter, message, fromLanguage, toLanguage
messages := make(chan string) messages := make(chan string)
defer close(messages) defer close(messages)
go extractMessage(messages) go streamResponse(w, messages)
cmd := exec.Command(linux, "translator/translate.py", message, fromLanguage, toLanguage) cmd := exec.Command(linux, "translator/translate.py", message, fromLanguage, toLanguage)
output, err := cmd.StdoutPipe() output, err := cmd.StdoutPipe()