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