package webhook import ( "net/http" "strings" "git.ohea.xyz/cursorius/server/config" "git.ohea.xyz/cursorius/server/jobscheduler" "git.ohea.xyz/cursorius/server/pipeline_executor" "github.com/go-playground/webhooks/v6/gitea" "github.com/op/go-logging" ) var log = logging.MustGetLogger("cursorius-server") func CreateWebhookHandler(runCh chan jobscheduler.Run, conf config.Config, mux *http.ServeMux) { mux.HandleFunc("/webhook/", func(w http.ResponseWriter, r *http.Request) { switch r.Method { case "POST": splitUrl := strings.Split(r.URL.Path, "/") if len(splitUrl) != 3 { log.Errorf("Webhook recieved with invalid url \"%v\", ignoring...", r.URL) return } // get URL path after /webhook/ // TODO: verify that this handles all valid URL formats webhookJobName := splitUrl[2] for jobName, jobConfig := range conf.Jobs { if webhookJobName == jobName { if jobConfig.Webhook == nil { log.Errorf("Matching job does not have webhook configuration, ignoring....") return } switch jobConfig.Webhook.Sender { case config.Gitea: hook, err := gitea.New(gitea.Options.Secret(jobConfig.Webhook.Secret)) if err != nil { log.Errorf("Could not create Gitea webhook handler: %v", err) return } payload, err := hook.Parse(r, gitea.PushEvent) if err != nil { if err == gitea.ErrEventNotFound { log.Info("Got webhook for unexpected event type, ignoring...") break } log.Errorf("Could not parse webhook: %v", err) return } log.Infof("Got webhook with payload %v", payload) switch payload.(type) { case gitea.PushPayload: pushPayload := payload.(gitea.PushPayload) pe := pipeline_executor.PipelineExecution{ Name: webhookJobName, Job: jobConfig, Ref: pushPayload.Ref, } pipeline_executor.ExecutePipeline(pe, conf.PipelineConf) } return default: log.Errorf("Job configured with unknown webhook sender \"%v\", igonring...", jobConfig.Webhook.Sender) return } } } log.Errorf("Not job configured with name \"%v\", required by webhook with url \"%v\", ignoring...", webhookJobName, r.URL) default: log.Errorf("Got request with method \"%v\", ignoring...", r.Method) } }) }