Add webhook

This commit is contained in:
Nise Void 2018-11-07 18:35:45 +01:00
parent 0d86e7ea2a
commit 29ecfb2b2a
Signed by: NiseVoid
GPG Key ID: FBA14AC83EA602F3
1 changed files with 35 additions and 2 deletions

37
main.go
View File

@ -2,12 +2,14 @@ package main
import ( import (
"bytes" "bytes"
"encoding/json"
"flag" "flag"
"html/template" "html/template"
"io/ioutil" "io/ioutil"
"log" "log"
"net/http" "net/http"
"os" "os"
"os/exec"
"path" "path"
"strconv" "strconv"
"strings" "strings"
@ -18,6 +20,8 @@ import (
func main() { func main() {
loadConfig() loadConfig()
_ = os.Setenv(`GIT_TERMINAL_PROMPT`, `0`)
if err := updateTemplate(); err != nil { if err := updateTemplate(); err != nil {
log.Fatal(`Failed to load template. (` + err.Error() + `)`) log.Fatal(`Failed to load template. (` + err.Error() + `)`)
} }
@ -30,6 +34,7 @@ var config struct {
Template string Template string
Pages string Pages string
Static string Static string
Webhook string
} }
func loadConfig() { func loadConfig() {
@ -37,21 +42,49 @@ func loadConfig() {
flag.StringVar(&config.Template, `template`, `template.html`, `The template used by mdsite`) flag.StringVar(&config.Template, `template`, `template.html`, `The template used by mdsite`)
flag.StringVar(&config.Pages, `pages`, `pages`, `The OS path used when searching a page`) flag.StringVar(&config.Pages, `pages`, `pages`, `The OS path used when searching a page`)
flag.StringVar(&config.Static, `static`, `static`, `The OS path used for static resource`) flag.StringVar(&config.Static, `static`, `static`, `The OS path used for static resource`)
flag.StringVar(&config.Webhook, `webhook`, ``, `The secret for webhooks to update the content`)
flag.Parse() flag.Parse()
} }
var t *template.Template var t *template.Template
func updateTemplate() error { func updateTemplate() error {
var err error tmpl, err := template.ParseFiles(config.Template)
t, err = template.ParseFiles(config.Template)
if err != nil { if err != nil {
return err return err
} }
t = tmpl
return nil return nil
} }
func serveRequest(w http.ResponseWriter, r *http.Request) { func serveRequest(w http.ResponseWriter, r *http.Request) {
if r.Method == http.MethodPost && config.Webhook != `` && r.URL.Path == `/hook` {
var input struct {
Secret string `json:"secret"`
}
err := json.NewDecoder(r.Body).Decode(&input)
_ = r.Body.Close()
if err != nil || input.Secret != config.Webhook {
w.WriteHeader(403)
return
}
err = exec.Command(`git`, `fetch`).Run()
if err == nil {
err = exec.Command(`git`, `reset`, `--hard`, `origin/master`).Run()
}
if err == nil {
err = updateTemplate()
}
if err != nil {
w.WriteHeader(500)
w.Write([]byte(`Update failed`))
}
return
}
if strings.HasPrefix(r.URL.Path, `/static/`) { if strings.HasPrefix(r.URL.Path, `/static/`) {
path := path.Join(config.Static, path.Clean(strings.TrimPrefix(r.URL.Path, `/static/`))) path := path.Join(config.Static, path.Clean(strings.TrimPrefix(r.URL.Path, `/static/`)))
http.ServeFile(w, r, path) http.ServeFile(w, r, path)