syz/bin/syz.go

94 lines
2.0 KiB
Go

package main
import (
"context"
"log/slog"
"net/http"
"os"
"os/signal"
"syscall"
"git.zhouxhere.com/zhouxhere/syz/config"
"git.zhouxhere.com/zhouxhere/syz/server"
"git.zhouxhere.com/zhouxhere/syz/store"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var rootCmd = &cobra.Command{
Use: "syz",
Short: "一个简单的个人所用的单点登录",
Run: func(cmd *cobra.Command, args []string) {
config := &config.Config{
Mode: viper.GetString("mode"),
Addr: viper.GetString("addr"),
Port: viper.GetInt("port"),
DSN: viper.GetString("dsn"),
}
if err := config.Validate(); err != nil {
panic(err)
}
ctx, cancel := context.WithCancel(context.Background())
store, err := store.NewStore(config.DSN)
if err != nil {
cancel()
slog.Error("store init failed", "err", err)
return
}
// if err := store.Migrate(ctx); err != nil {
// cancel()
// slog.Error("store migrate failed", "err", err)
// return
// }
s := server.NewServer(ctx, config, store)
c := make(chan os.Signal, 1)
signal.Notify(c, os.Interrupt, syscall.SIGTERM)
if err := s.Start(ctx); err != nil {
if err != http.ErrServerClosed {
slog.Error("server start failed", "err", err)
cancel()
}
}
go func() {
<-c
s.Stop(ctx)
cancel()
}()
<-ctx.Done()
},
}
func init() {
viper.SetDefault("mode", "dev")
viper.SetDefault("addr", "0.0.0.0")
viper.SetDefault("port", 8080)
rootCmd.PersistentFlags().String("mode", "dev", `mode of server, can be "prod" or "dev"`)
rootCmd.PersistentFlags().String("addr", "0.0.0.0", "address of server")
rootCmd.PersistentFlags().Int("port", 8080, "port of server")
rootCmd.PersistentFlags().String("dsn", "postgresql://syz:syz_passwd@localhost:5432/syz?sslmode=disable", "database source name")
if err := viper.BindPFlags(rootCmd.PersistentFlags()); err != nil {
panic(err)
}
viper.SetEnvPrefix("syz")
viper.AutomaticEnv()
}
func main() {
if err := rootCmd.Execute(); err != nil {
panic(err)
}
}