package Messages import ( "encoding/base64" "encoding/json" "net/http" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Database" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Models" "git.tovijaeschke.xyz/tovi/Envelope/Backend/Util" ) type rawMessageData struct { MessageData Models.MessageData `json:"message_data"` Messages []Models.Message `json:"message"` } // CreateMessage sends a message func CreateMessage(w http.ResponseWriter, r *http.Request) { var ( messagesData []rawMessageData messageData rawMessageData decodedFile []byte fileName string err error ) err = json.NewDecoder(r.Body).Decode(&messagesData) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } for _, messageData = range messagesData { if messageData.MessageData.Data == "" { decodedFile, err = base64.StdEncoding.DecodeString(messageData.MessageData.Attachment.Data) fileName, err = Util.WriteFile(decodedFile) messageData.MessageData.Attachment.FilePath = fileName } err = Database.CreateMessageData(&messageData.MessageData) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } err = Database.CreateMessages(&messageData.Messages) if err != nil { http.Error(w, "Error", http.StatusInternalServerError) return } } w.WriteHeader(http.StatusOK) }