package main import ( "context" "fmt" "log" "net/http" "os" "os/signal" "rpi-ci-led/pkg/config" "rpi-ci-led/pkg/database" "rpi-ci-led/pkg/led" "rpi-ci-led/pkg/websocket" "rpi-ci-led/pkg/ws2812b" "rpi-ci-led/route/routes" "syscall" "time" "git.trj.tw/golang/argparse" "github.com/joho/godotenv" ) func main() { fmt.Println("GO ci hook") godotenv.Load() var configFile string var dbPath string // argument parser argParser := argparse.New() argParser.Help("h", "help") argParser.StringVar(&configFile, "", "f", "config", "config yaml file path", nil) argParser.StringVar(&dbPath, "", "d", "db", "database file path", nil) if err := argParser.Parse(os.Args); err != nil { log.Fatal(err) } if err := config.Load(configFile); err != nil { log.Fatal(err) } if err := database.New(dbPath); err != nil { log.Fatal(err) } conf := config.Get() socket, err := websocket.NewClient(conf.Remote.WSLoc) if err != nil { log.Fatal(err) } ledsvc, err := led.Init(conf.LED.Pin, conf.LED.Count) if err != nil { log.Fatal(err) } router := routes.New() routes.SetRoutes(router) svc := new(http.Server) svc.Addr = fmt.Sprintf(":%d", conf.Server.Port) svc.Handler = router lock := make(chan os.Signal) signal.Notify(lock, syscall.SIGINT, syscall.SIGTERM) // main go func() { if err := svc.ListenAndServe(); err != nil && err != http.ErrServerClosed { log.Fatal(err) } }() go func() { if err := socket.Listen(); err != nil { log.Fatal(err) } lock <- syscall.SIGQUIT }() go func() { ledsvc.Run() }() // start ws client connect to server <-lock fmt.Printf("Before process exit, close all connection\n") ctx, cancel := context.WithTimeout(context.Background(), time.Second*3) defer cancel() if err := svc.Shutdown(ctx); err != nil { log.Fatal(err) } socket.Close() ledsvc.Stop() ws2812b.Close() }