Tidy and add json content type to replies

So some minor tweaks and add the content type application/json to the
replies.
This commit is contained in:
Felix Niederwanger 2022-12-29 15:11:18 +01:00
parent cef1c1540a
commit c52fc3fbb5
Signed by: phoenix
GPG key ID: 31860289A704FB3C

View file

@ -8,10 +8,11 @@ import (
"log"
"net/http"
"os"
"os/signal"
"syscall"
)
var cf Config
var hooks []Hook
type Handler func(http.ResponseWriter, *http.Request)
@ -24,6 +25,17 @@ func usage() {
fmt.Println("The program loads the given yaml files for webhook definitions")
}
// awaits SIGINT or SIGTERM
func awaitTerminationSignal() {
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, syscall.SIGINT, syscall.SIGTERM)
go func() {
sig := <-sigs
fmt.Println(sig)
os.Exit(1)
}()
}
func main() {
cf.SetDefaults()
if len(os.Args) < 2 {
@ -68,7 +80,7 @@ func main() {
http.HandleFunc(hook.Route, createHandler(hook))
}
// TODO: Await termination signal
awaitTerminationSignal()
log.Printf("Launching webserver on %s", cf.Settings.BindAddress)
log.Fatal(http.ListenAndServe(cf.Settings.BindAddress, nil))
@ -80,9 +92,10 @@ func createHandler(hook Hook) Handler {
log.Printf("GET %s %s", r.RemoteAddr, hook.Name)
// Check for available slots
if hook.TryLock() == false {
if !hook.TryLock() {
log.Printf("ERR: \"%s\" max concurrency reached", hook.Name)
// 503 - Service Unavailable
// Return a 503 - Service Unavailable error
w.Header().Add("Content-Type", "application/json")
w.Header().Add("Retry-After", "120") // Suggest to retry after 2 minutes
w.WriteHeader(503)
fmt.Fprintf(w, "{\"status\":\"fail\",\"reason\":\"max concurrency reached\"}")
@ -90,6 +103,7 @@ func createHandler(hook Hook) Handler {
}
if hook.Background { // Execute command in background
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "{\"status\":\"ok\"}")
go func() {
@ -104,9 +118,11 @@ func createHandler(hook Hook) Handler {
defer hook.Unlock()
if err := hook.Run(); err != nil {
log.Printf("ERR: \"%s\" exec failure: %s", hook.Name, err)
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(500)
fmt.Fprintf(w, "{\"status\":\"fail\",\"reason\":\"program error\"}")
} else {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "{\"status\":\"ok\"}")
}
@ -116,6 +132,7 @@ func createHandler(hook Hook) Handler {
func createHealthHandler() Handler {
return func(w http.ResponseWriter, r *http.Request) {
w.Header().Add("Content-Type", "application/json")
w.WriteHeader(200)
fmt.Fprintf(w, "{\"status\":\"ok\"}")
}
@ -124,7 +141,7 @@ func createHealthHandler() Handler {
func createDefaultHandler() Handler {
return func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(200)
fmt.Fprintf(w, "weblug")
fmt.Fprintf(w, "weblug - simple webhook handler")
}
}