simplified
This commit is contained in:
parent
166c95b7bb
commit
f2ee3fcb7f
58
main.go
58
main.go
|
@ -20,63 +20,21 @@ type Message struct {
|
|||
To string `json:"to"`
|
||||
}
|
||||
|
||||
type StreamResponse struct {
|
||||
From string `json:"from"`
|
||||
To string `json:"to"`
|
||||
CreatedAt string `json:"createdAt"`
|
||||
Response string `json:"response"`
|
||||
}
|
||||
|
||||
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
|
||||
func extractMessage(message string) (string, error) {
|
||||
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: extractedMessage,
|
||||
}
|
||||
|
||||
jsonResp, err := json.Marshal(response)
|
||||
err := json.Unmarshal([]byte(message), &temp)
|
||||
if err != nil {
|
||||
return `{"response": "Error in preparing the message."}`
|
||||
}
|
||||
return string(jsonResp)
|
||||
}
|
||||
|
||||
func streamResponse(w http.ResponseWriter, messages <-chan string) {
|
||||
w.Header().Set("Content-Type", "application/json; 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
|
||||
return "", fmt.Errorf("failed to unmarshal message: %v", err)
|
||||
}
|
||||
|
||||
for msg := range messages {
|
||||
formattedMessage := createStreamResponse("fromLanguage", "toLanguage", msg) // Adjust as needed
|
||||
fmt.Fprintf(w, " %s\n\n", formattedMessage)
|
||||
flusher.Flush()
|
||||
response, exists := temp["response"]
|
||||
if !exists {
|
||||
return "", fmt.Errorf("no 'response' field found in the message")
|
||||
}
|
||||
|
||||
return fmt.Sprintf("%v", response), nil
|
||||
}
|
||||
|
||||
func downloadPackages(w http.ResponseWriter, fromLanguage, toLanguage string) {
|
||||
|
|
Loading…
Reference in New Issue