bottin-agenda/cmd/api.go

102 lines
2.3 KiB
Go
Raw Normal View History

2023-05-29 17:58:23 -04:00
package cmd
import (
"crypto/subtle"
"fmt"
"log"
2023-06-03 20:16:41 -04:00
"git.agecem.com/agecem/bottin-agenda/data"
2023-05-29 17:58:23 -04:00
"git.agecem.com/agecem/bottin-agenda/handlers"
2023-06-03 19:48:37 -04:00
bottindata "git.agecem.com/agecem/bottin/v5/data"
2023-05-29 17:58:23 -04:00
"github.com/labstack/echo/v4"
"github.com/labstack/echo/v4/middleware"
"github.com/spf13/cobra"
"github.com/spf13/viper"
)
var (
apiPort int
apiKey string
)
// apiCmd represents the api command
var apiCmd = &cobra.Command{
Use: "api",
Short: "Démarrer le serveur API",
Args: cobra.ExactArgs(0),
Run: func(cmd *cobra.Command, args []string) {
// TODO migrer à viper.Unmarshal(&models.Config)
2023-05-29 17:58:23 -04:00
apiKey = viper.GetString("api.key")
apiPort = viper.GetInt("api.port")
bottinApiKey := viper.GetString("bottin.api.key")
bottinApiHost := viper.GetString("bottin.api.host")
bottinApiProtocol := viper.GetString("bottin.api.protocol")
bottinApiPort := viper.GetInt("bottin.api.port")
// Using bottin's API client
bottinConnection := bottindata.NewApiClient(
2023-05-29 17:58:23 -04:00
bottinApiKey,
bottinApiHost,
bottinApiProtocol,
bottinApiPort,
)
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
2023-06-08 21:05:25 -04:00
e.POST("/v3/seed/", handlers.PostSeed)
2023-06-06 02:16:54 -04:00
2023-06-08 21:05:25 -04:00
e.GET("/v3/health/", handlers.GetHealth)
2023-05-29 17:58:23 -04:00
2023-06-08 21:05:25 -04:00
e.GET("/v3/transactions/", handlers.GetTransactions)
e.POST("/v3/transactions/", handlers.PostTransactions)
2023-05-29 17:58:23 -04:00
// Check bottin is ready
2023-06-03 19:48:37 -04:00
bottinHealthResponse, err := bottinConnection.GetHealth()
2023-05-29 17:58:23 -04:00
if err != nil {
2023-06-03 20:16:41 -04:00
log.Fatalf("[bottin] bottinConnection.GetHealth(): %s", err)
2023-05-29 17:58:23 -04:00
}
2023-06-03 20:16:41 -04:00
log.Println("[bottin] ok: ", bottinHealthResponse)
// Check database is ready
dataClient, err := data.NewDataClientFromViper()
if err != nil {
log.Fatalf("[bottin-agenda db] data.NewDataclientFromViper(): %s", err)
}
defer dataClient.DB.Close()
if err := dataClient.DB.Ping(); err != nil {
log.Fatalf("[bottin-agenda db] dataClient.DB.Ping() failed: %s", err)
2023-06-03 20:16:41 -04:00
} else {
log.Println("[bottin-agenda db] ok")
}
2023-05-29 17:58:23 -04:00
if _, err = dataClient.Seed(); err != nil {
log.Fatalf("[bottin-agenda db] dataClient.Seed() failed: %s", err)
}
2023-05-29 17:58:23 -04:00
// Execution
e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", apiPort)))
},
}
func init() {
rootCmd.AddCommand(apiCmd)
}