coverage/server/upload.go

77 lines
1.7 KiB
Go

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")
params, ok := getAllParams(w, r, uploadType)
coverage := r.Form.Get("coverage")
if secretEnv != secret && secretEnv != "" {
http.Error(w, "invalid secret provided", http.StatusUnauthorized)
return
}
if !ok {
return
}
if coverage == "" {
http.Error(w, "request param coverage must be present", 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(params[0], params[1], params[2], 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")
}