package server import ( "fmt" "io" "net/http" "os" "gitea.teamortix.com/team-ortix/coverage/db" ) const coverageSecret = "COVERAGE_SECRET" var secretEnv = os.Getenv(coverageSecret) func uploadBranch(w http.ResponseWriter, r *http.Request) { upload(w, r, "branch", db.UploadBranchData) } func uploadPull(w http.ResponseWriter, r *http.Request) { upload(w, r, "pull", db.UploadPullData) } func upload(w http.ResponseWriter, r *http.Request, uploadType string, uploadFunc func(string, string, string, string, string) error) { if r.Method != "POST" { return } err := r.ParseMultipartForm(5 << 20) if err != nil { http.Error(w, "file too large", http.StatusRequestEntityTooLarge) return } err = r.ParseForm() if err != nil { http.Error(w, "could not parse form", http.StatusBadRequest) return } secret := r.Form.Get("secret") namespace := r.Form.Get("namespace") project := r.Form.Get("project") uploadValue := r.Form.Get(uploadType) coverage := r.Form.Get("coverage") if secretEnv != secret && secretEnv != "" { http.Error(w, "invalid secret provided", http.StatusUnauthorized) return } if namespace == "" || project == "" || uploadValue == "" || coverage == "" { http.Error(w, fmt.Sprintf("request params [namespace project, %s, coverage] must all be present", uploadType), http.StatusBadRequest) return } report, _, err := r.FormFile("report") if err != nil { http.Error(w, "could not parse report parameter", http.StatusBadRequest) return } bytes, err := io.ReadAll(report) if err != nil { http.Error(w, fmt.Sprintf("could not read file: %v", err), http.StatusBadRequest) return } err = uploadFunc(namespace, project, uploadValue, coverage, string(bytes)) if err != nil { http.Error(w, fmt.Sprintf("could not upload data to database: %v", err), http.StatusInternalServerError) return } fmt.Fprintln(w, "uploaded") }