package main import ( "encoding/json" "fmt" "io" "log" "net/http" "os" "os/exec" "path" "runtime" "gitea.urkob.com/urko/gitea-webhook-listener/kit/config" ) func main() { cfgFile := os.Getenv("CONFIG_FILE") if cfgFile == "" { // Get root path _, filename, _, _ := runtime.Caller(0) cfgFile = path.Join(path.Dir(filename), "configs", "app.yml") } cfg, err := config.LoadConfig(cfgFile) if err != nil { log.Fatalf("Error loading config: %v", err) } http.HandleFunc("/", handlePayload(cfg.Secret, cfg.Scripts)) http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil) } func handlePayload(secret string, scripts map[string]config.ConfigScript) func(w http.ResponseWriter, r *http.Request) { return (func(w http.ResponseWriter, r *http.Request) { // Read the request body body, err := io.ReadAll(r.Body) if err != nil { http.Error(w, "Failed to read request body", http.StatusBadRequest) return } defer r.Body.Close() authHeader := r.Header.Get("Authorization") log.Println("authHeader", authHeader) if authHeader != secret { http.Error(w, "Signatures didn't match", http.StatusUnauthorized) return } if !r.URL.Query().Has("project") { http.Error(w, "", http.StatusBadRequest) return } project := r.URL.Query().Get("project") scr, found := scripts[project] if !found { http.Error(w, "not found", http.StatusNotFound) return } log.Println("body", body) // Parse the JSON payload var payload interface{} err = json.Unmarshal(body, &payload) if err != nil { http.Error(w, "Failed to parse JSON payload", http.StatusBadRequest) return } // TODO: Do something with the payload fmt.Fprintf(w, "I got some JSON: %v", payload) if err := execute(scr.BinaryPath, scr.ScriptPath); err != nil { panic(err) } }) } func execute(binaryPath, scriptPath string) error { cmd := exec.Command(binaryPath, scriptPath) cmd.Stdout = os.Stdout cmd.Stderr = os.Stderr if err := cmd.Run(); err != nil { return fmt.Errorf("cmd.Run %w", err) } return nil }