Skip to content

Instantly share code, notes, and snippets.

@CapacitorSet
Created March 11, 2019 10:49
Show Gist options
  • Save CapacitorSet/6ed2ab2598f6e95ffb88eb76a0b33fe7 to your computer and use it in GitHub Desktop.
Save CapacitorSet/6ed2ab2598f6e95ffb88eb76a0b33fe7 to your computer and use it in GitHub Desktop.
A tiny webhook server that runs a bash script upon pushes to master.
package main
import (
"log"
"net/http"
"os"
"os/exec"
"gopkg.in/go-playground/webhooks.v5/github"
)
const path = "/"
func onPush(w http.ResponseWriter, payload github.PushPayload) {
if (payload.Ref != "refs/heads/master") {
log.Printf("No-op: ref '%s' isn't of interest", payload.Ref)
return
}
cmd := exec.Command("/bin/bash", "on-push.sh")
cmd.Stdout = w
cmd.Stderr = w
err := cmd.Run()
if err != nil {
log.Println("Bash exec error: %s", err.Error())
return
}
log.Println("Bash exec successful")
}
func main() {
secret := os.Getenv("GITHUB_WEBHOOK_SECRET")
if secret == "" {
log.Println("Please provide a webhook secret with the GITHUB_WEBHOOK_SECRET environment variable.")
return
}
hook, _ := github.New(github.Options.Secret(secret))
http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
log.Println("New payload")
payload, err := hook.Parse(r, github.PushEvent)
if err != nil {
if err != github.ErrEventNotFound {
log.Println("Error: %#v\n", err)
}
return
}
switch typedPayload := payload.(type) {
case github.PushPayload:
onPush(w, typedPayload)
default:
log.Printf("Unknown payload type.\n%#v\n", typedPayload)
}
})
log.Println("Listening")
http.ListenAndServe(":4000", nil)
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment