package cmd import ( "crypto/subtle" "fmt" "log" "git.agecem.com/agecem/bottin/v4/data" "git.agecem.com/agecem/bottin/v4/handlers" "github.com/labstack/echo/v4" "github.com/labstack/echo/v4/middleware" "github.com/spf13/cobra" "github.com/spf13/viper" ) var ( apiPort int apiKey string ) // serverCmd represents the server command var serverCmd = &cobra.Command{ Use: "server", Short: "Démarrer le serveur API", Run: func(cmd *cobra.Command, args []string) { e := echo.New() // Middlewares e.Pre(middleware.AddTrailingSlash()) if apiKey != "" { e.Use(middleware.KeyAuth(func(key string, c echo.Context) (bool, error) { return subtle.ConstantTimeCompare([]byte(key), []byte(apiKey)) == 1, nil })) } // Routes e.GET("/v4/", handlers.GetV4) e.POST("/v4/membres/", handlers.PostMembres) e.GET("/v4/membres/:membre_id/", handlers.ReadMembre) e.PUT("/v4/membres/:membre_id/prefered_name/", handlers.PutMembrePreferedName) e.POST("/v4/programmes/", handlers.PostProgrammes) e.POST("/v4/seed/", handlers.PostSeed) // Execution connection := data.PostgresConnection{ User: viper.GetString("db.user"), Password: viper.GetString("db.password"), Host: viper.GetString("db.host"), Database: viper.GetString("db.database"), Port: viper.GetInt("db.port"), } client, err := data.NewDataClient(connection) if err != nil { log.Fatalf("Could not establish database connection.\n Error: %s\n", err) } err = client.DB.Ping() if err != nil { log.Fatalf("Database was supposed to be ready but Ping() failed.\n Error: %s\n", err) } client.DB.Close() e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", apiPort))) }, } func init() { rootCmd.AddCommand(serverCmd) // api.key serverCmd.Flags().StringVar( &apiKey, "api-key", "bottin", "API server key. Leave empty for no key auth. (config: 'api.key')") // api.port serverCmd.Flags().IntVar( &apiPort, "api-port", 1312, "API server port (config:'api.port')") // db.database serverCmd.Flags().String("db-database", "bottin", "Postgres database (config:'db.database')") viper.BindPFlag("db.database", serverCmd.Flags().Lookup("db-database")) // db.host serverCmd.Flags().String("db-host", "", "Postgres host (config:'db.host')") viper.BindPFlag("db.host", serverCmd.Flags().Lookup("db-host")) // db.password serverCmd.Flags().String("db-password", "", "Postgres password (config:'db.password')") viper.BindPFlag("db.password", serverCmd.Flags().Lookup("db-password")) // db.port serverCmd.Flags().Int("db-port", 5432, "Postgres port (config:'db.port')") viper.BindPFlag("db.port", serverCmd.Flags().Lookup("db-port")) // db.user serverCmd.Flags().String("db-user", "", "Postgres user (config:'db.user')") viper.BindPFlag("db.user", serverCmd.Flags().Lookup("db-user")) }