fix: load endless and block main with ctx.Done()
This commit is contained in:
parent
f6e4e64e81
commit
d22a6816c4
34
main.go
34
main.go
|
@ -1,6 +1,7 @@
|
||||||
package main
|
package main
|
||||||
|
|
||||||
import (
|
import (
|
||||||
|
"context"
|
||||||
"encoding/json"
|
"encoding/json"
|
||||||
"fmt"
|
"fmt"
|
||||||
"io"
|
"io"
|
||||||
|
@ -8,15 +9,21 @@ import (
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
"os/exec"
|
"os/exec"
|
||||||
|
"os/signal"
|
||||||
"path"
|
"path"
|
||||||
"runtime"
|
"runtime"
|
||||||
"strings"
|
"strings"
|
||||||
|
"syscall"
|
||||||
|
|
||||||
"gitea.urkob.com/urko/gitea-webhook-listener/internal"
|
"gitea.urkob.com/urko/gitea-webhook-listener/internal"
|
||||||
"gitea.urkob.com/urko/gitea-webhook-listener/kit/config"
|
"gitea.urkob.com/urko/gitea-webhook-listener/kit/config"
|
||||||
)
|
)
|
||||||
|
|
||||||
func main() {
|
func main() {
|
||||||
|
var err error
|
||||||
|
ctx, cancel := context.WithCancel(signalContext(context.Background()))
|
||||||
|
defer cancel()
|
||||||
|
|
||||||
cfgFile := os.Getenv("CONFIG_FILE")
|
cfgFile := os.Getenv("CONFIG_FILE")
|
||||||
if cfgFile == "" {
|
if cfgFile == "" {
|
||||||
// Get root path
|
// Get root path
|
||||||
|
@ -28,8 +35,17 @@ func main() {
|
||||||
log.Fatalf("Error loading config: %v", err)
|
log.Fatalf("Error loading config: %v", err)
|
||||||
}
|
}
|
||||||
http.HandleFunc("/", handlePayload(cfg.Secret, cfg.Projects))
|
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)
|
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) {
|
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
|
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
|
||||||
|
}
|
||||||
|
|
Loading…
Reference in New Issue