hooker/hooker.go
2023-09-19 23:47:19 +03:00

102 lines
1.8 KiB
Go

package main
import (
"fmt"
"log"
"net/http"
"os"
"strconv"
"sync"
"time"
)
/*
Listen for git web hooks and then execute a script.
*/
type TaskDefErr struct {
message string
}
func (e *TaskDefErr) Error() string {
return e.message
}
type TaskManifest struct {
Owner string
RepoID uint64
Auth string
Command string // Path to executable
Lock *sync.Mutex
}
var httpServer http.Server
var task TaskManifest
func InitHTTPHandler(handler *http.ServeMux) *LoggingHTTPHandler {
auth := NewAuth(handler)
loggingHandler := NewLogger(&auth)
return &loggingHandler
}
// Try to get an env var, if not set, panic or fatal
func getEnv(name string) string {
varVal := os.Getenv(name)
if varVal == "" {
panic(fmt.Sprintf("required %s env variable is not set", name))
}
return varVal
}
func InitTask() TaskManifest {
RepoID := getEnv("REPO_ID")
repoID, err := strconv.ParseUint(RepoID, 10, 64)
if err != nil {
panic("REPO_ID is not a valid int")
}
return TaskManifest{
Command: getEnv("CMD"),
Owner: getEnv("OWNER"),
Auth: getEnv("AUTH"),
RepoID: repoID,
Lock: &sync.Mutex{},
}
}
func init() {
TAG := "[ init ]"
l := func(msg string) {
log.Println(TAG, msg)
}
l("starting")
l("Validating Task")
task = InitTask()
l("Registering handlers")
mux := http.NewServeMux()
mux.HandleFunc("/", handleRoot)
handler := InitHTTPHandler(mux)
httpServer = http.Server{
ReadTimeout: time.Second * 5,
WriteTimeout: time.Second * 5,
Addr: ":4184",
Handler: handler,
}
}
func main() {
log.Println("Task", task)
log.Printf("Listening on %s", httpServer.Addr)
log.Fatal(httpServer.ListenAndServe())
log.Println("Server Stopped")
}