fix: load endless and block main with ctx.Done()

This commit is contained in:
Urko. 2024-05-30 07:03:37 +02:00
parent f6e4e64e81
commit d22a6816c4
1 changed files with 33 additions and 1 deletions

34
main.go
View File

@ -1,6 +1,7 @@
package main
import (
"context"
"encoding/json"
"fmt"
"io"
@ -8,15 +9,21 @@ import (
"net/http"
"os"
"os/exec"
"os/signal"
"path"
"runtime"
"strings"
"syscall"
"gitea.urkob.com/urko/gitea-webhook-listener/internal"
"gitea.urkob.com/urko/gitea-webhook-listener/kit/config"
)
func main() {
var err error
ctx, cancel := context.WithCancel(signalContext(context.Background()))
defer cancel()
cfgFile := os.Getenv("CONFIG_FILE")
if cfgFile == "" {
// Get root path
@ -28,8 +35,17 @@ func main() {
log.Fatalf("Error loading config: %v", err)
}
http.HandleFunc("/", handlePayload(cfg.Secret, cfg.Projects))
go func() {
err = http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil)
}()
log.Printf("server is up on %d\n", cfg.Port)
http.ListenAndServe(fmt.Sprintf(":%d", cfg.Port), nil)
<-ctx.Done()
if err != nil {
log.Println("some error happened", err)
}
log.Println("server shutdown")
}
func handlePayload(secret string, projects map[string][]config.ConfigScript) func(w http.ResponseWriter, r *http.Request) {
@ -101,3 +117,19 @@ func execute(command string, args ...string) error {
return nil
}
func signalContext(ctx context.Context) context.Context {
ctx, cancel := context.WithCancel(ctx)
sigs := make(chan os.Signal, 1)
signal.Notify(sigs, os.Interrupt, syscall.SIGINT, syscall.SIGTERM)
go func() {
<-sigs
signal.Stop(sigs)
close(sigs)
cancel()
}()
return ctx
}