Skip to content

Instantly share code, notes, and snippets.

@billryan
Last active August 28, 2023 08:17
Show Gist options
  • Save billryan/827a0c0af06aa18f248421f198cc5fe9 to your computer and use it in GitHub Desktop.
Save billryan/827a0c0af06aa18f248421f198cc5fe9 to your computer and use it in GitHub Desktop.
GitHub webhook with Go
package main
import (
"fmt"
"io/ioutil"
"log"
"net/http"
"gopkg.in/go-playground/webhooks.v5/github"
"os"
"os/exec"
)
const (
path = "/xxx"
GIT_BRANCH = "gh-pages"
)
var repoStaticDir = map[string]string{
"site1": "/var/www/site1/",
"site2": "/var/www/site2/",
}
func main() {
hook, _ := github.New(github.Options.Secret("yoursecret"))
http.HandleFunc(path, func(w http.ResponseWriter, r *http.Request) {
payload, err := hook.Parse(r, github.PageBuildEvent, github.PushEvent)
if err != nil {
if err == github.ErrEventNotFound {
// ok event wasn;t one of the ones asked to be parsed
}
}
switch payload.(type) {
case github.PageBuildPayload:
pageBuild := payload.(github.PageBuildPayload)
// Do whatever you want from here...
// fmt.Printf("%+v", pageBuild)
fmt.Printf("received page build event...\n")
repoName := pageBuild.Repository.Name
cloneUrl := pageBuild.Repository.CloneURL
destDir := repoStaticDir[repoName]
handler(cloneUrl, destDir)
case github.PushPayload:
push := payload.(github.PushPayload)
// Do whatever you want from here...
// fmt.Printf("%+v", push)
repoName := push.Repository.Name
fmt.Printf("repo %s received git push event...\n", repoName)
}
})
http.ListenAndServe("127.0.0.1:8001", nil)
}
func handler(url, dir string) {
tempDir, err := ioutil.TempDir("", "temp-git-")
if err != nil {
log.Fatal(err)
}
defer os.RemoveAll(tempDir) // clean up
gitArgs := []string{"clone", url, "--branch", GIT_BRANCH, "--depth", "1", "--single-branch", tempDir}
fmt.Printf("git clone with args %v\n", gitArgs)
execHandler("git", gitArgs...)
rsyncArgs := []string{"-avP", "--delete", tempDir + "/", dir + "/"}
fmt.Printf("rsync with args %v\n", rsyncArgs)
execHandler("rsync", rsyncArgs...)
}
func execHandler(app string, args ...string) {
out, err := exec.Command(app, args...).Output()
if err != nil {
log.Fatal(err)
}
fmt.Printf("The output is %s\n", out)
}
[Unit]
Description=Webhook Service
After=network.target
Wants=network.target
[Service]
# This service runs as root. You may consider to run it as another user for security concerns.
# User=webhook
# Group=webhook
Type=simple
PIDFile=/run/webhook.pid
ExecStart=/usr/local/bin/webhook
Restart=on-failure
RestartSec=3
# Don't restart in the case of configuration error
RestartPreventExitStatus=23
[Install]
WantedBy=multi-user.target
@billryan
Copy link
Author

soluprotmutdb.sql.mp4

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment