server/receiver/save.go

64 lines
1.7 KiB
Go
Raw Normal View History

package main
import (
"bufio"
"io/ioutil"
"log"
"net/http"
"os"
"path"
)
var SubmissionDir = "./submissions/"
2017-11-22 00:52:08 +00:00
var TmpSubmissionDir string
func saveTeamFile(p string, w http.ResponseWriter, r *http.Request) bool {
if len(SubmissionDir) < 1 || len(p) < 1 {
http.Error(w, "{\"errmsg\":\"Requête invalide.\"}", http.StatusBadRequest)
return false
2017-11-22 00:52:08 +00:00
} else if len(p) <= 0 {
log.Println("EMPTY $EXERCICE RECEIVED:", p)
http.Error(w, "{\"errmsg\":\"Internal server error. Please retry in few seconds.\"}", http.StatusInternalServerError)
return false
} else if _, err := os.Stat(path.Join(SubmissionDir, p)); !os.IsNotExist(err) {
// Previous submission not treated
2017-11-22 00:52:08 +00:00
http.Error(w, "{\"errmsg\":\"Du calme ! une requête est déjà en cours de traitement.\"}", http.StatusPaymentRequired)
return false
2019-01-17 15:55:54 +00:00
} else if err = saveFile(path.Join(SubmissionDir, p), r); err != nil {
2017-11-22 00:52:08 +00:00
log.Println("Unable to handle submission file:", err)
http.Error(w, "{\"errmsg\":\"Internal server error. Please retry in few seconds.\"}", http.StatusInternalServerError)
return false
}
2017-11-22 00:52:08 +00:00
return true
}
2017-11-22 00:52:08 +00:00
func saveFile(p string, r *http.Request) error {
dirname := path.Dir(p)
if _, err := os.Stat(dirname); os.IsNotExist(err) {
if err = os.MkdirAll(dirname, 0751); err != nil {
return err
}
}
// Write content to temp file
tmpfile, err := ioutil.TempFile(TmpSubmissionDir, "")
if err != nil {
return err
}
writer := bufio.NewWriter(tmpfile)
reader := bufio.NewReader(r.Body)
2019-01-17 15:55:54 +00:00
if _, err = reader.WriteTo(writer); err != nil {
return err
}
writer.Flush()
tmpfile.Close()
2019-01-17 15:55:54 +00:00
if err = os.Rename(tmpfile.Name(), p); err != nil {
log.Println("[ERROR] Unable to move file: ", err)
2017-11-22 00:52:08 +00:00
return err
}
return nil
}