github.com/seeker-insurance/kit@v0.0.13/cmd/api/api.go (about) 1 package api 2 3 import ( 4 "github.com/seeker-insurance/kit/cmd/migrate" 5 "github.com/seeker-insurance/kit/log" 6 "github.com/seeker-insurance/kit/web/server" 7 "github.com/spf13/cobra" 8 "github.com/spf13/viper" 9 ) 10 11 var ( 12 apiArgs = []string{"port", "secret"} 13 14 //ApiCmd represents the api command 15 Port int 16 Host string 17 checkMigs bool 18 ) 19 20 var ApiCmd = &cobra.Command{ 21 Use: "api", 22 Short: "Run the API server", 23 Long: ``, 24 Run: run, 25 } 26 27 func init() { 28 ApiCmd.PersistentFlags().IntVar(&Port, "port", 3000, "port to attach server") 29 ApiCmd.PersistentFlags().String("secret", "", "secret key used for token hashing") 30 ApiCmd.PersistentFlags().BoolVar(&checkMigs, "check-migrations", true, "check pending migrations before starting server") 31 ApiCmd.PersistentFlags().StringVar(&Host, "host", "", "the host of this api eg, http://foo.ngrok.io") 32 33 for _, a := range apiArgs { 34 viper.BindPFlag(a, ApiCmd.PersistentFlags().Lookup(a)) 35 viper.BindEnv(a) 36 } 37 } 38 39 func run(cmd *cobra.Command, args []string) { 40 if checkMigs { 41 checkMigrations() 42 } 43 44 if viper.GetInt("port") > 0 { 45 Port = viper.GetInt("port") 46 } 47 48 if Host == "" { 49 Host = viper.GetString("HOST") 50 } 51 52 log.Infof("Serving API on port %d...", Port) 53 54 server.Start(Port, Host) 55 } 56 57 func checkMigrations() { 58 if c, err := migrate.PendingMigrationCount(); err != nil { 59 log.Fatal(err) 60 } else if c > 0 { 61 log.Fatalf("%d Pending Migration(s), run migrations or use check-migrations=0", c) 62 } 63 }