coverage/server/server.go

78 lines
2.1 KiB
Go

package server
import (
"fmt"
"log"
"net/http"
"strconv"
"gitea.teamortix.com/team-ortix/coverage/pill"
"github.com/gorilla/mux"
)
func StartServer(port string) {
r := mux.NewRouter()
r.HandleFunc("/badge/{percentage}", handleBadge)
r.HandleFunc("/redirect", handleRedirect)
r.Handle("/report/branch/{namespace}/{project}/{branch}", AuthorizationMiddleware(handleBranchReport))
r.Handle("/report/pulls/{namespace}/{project}/{pull}", AuthorizationMiddleware(handlePullReport))
r.HandleFunc("/badge/branch/{namespace}/{project}/{branch}", handleBadgeBranch)
r.HandleFunc("/badge/pulls/{namespace}/{project}/{pull}", handlePullBadge)
r.HandleFunc("/upload/branch/{namespace}/{project}/{branch}", uploadBranch)
r.HandleFunc("/upload/pulls/{namespace}/{project}/{pull}", uploadPull)
portStr := fmt.Sprintf(":%s", port)
err := http.ListenAndServe(portStr, r)
if err != nil {
log.Fatalf("could not start server: %v", err)
}
}
func handleBadge(w http.ResponseWriter, r *http.Request) {
percentString, ok := mux.Vars(r)["percentage"]
if !ok {
http.Error(w, "could not find percentage in path", http.StatusBadRequest)
return
}
percent, err := strconv.ParseFloat(percentString, 64)
var p pill.Pill
if err != nil {
p = pill.UnknownPill()
} else {
p = pill.NewPill(percent / 100)
}
w.Header().Set("Content-Type", "image/svg+xml")
err = p.Execute(w)
if err != nil {
http.Error(w, fmt.Sprintf("could not write pill: %v", err), http.StatusInternalServerError)
return
}
}
func getAllParams(w http.ResponseWriter, r *http.Request, thirdParam string) ([3]string, bool) {
vars := mux.Vars(r)
namespace, ok := vars["namespace"]
if !ok {
http.Error(w, "Path 'namespace' not found", http.StatusBadRequest)
return [3]string{}, false
}
project, ok := vars["project"]
if !ok {
http.Error(w, "Path 'project' not found", http.StatusBadRequest)
return [3]string{}, false
}
third, ok := vars[thirdParam]
if !ok {
http.Error(w, fmt.Sprintf("Path '%s' not found", thirdParam), http.StatusBadRequest)
return [3]string{}, false
}
return [3]string{namespace, project, third}, true
}