bottin-agenda/cmd/api.go
Victor Lacasse-Beaudoin 660d8826e2 Implémenter POST /transaction
Ajouter data#ApiClient.InsertTransactions()

Fix form action

Ajouter séparateur entre description et formulaire

Ajouter webhandlers#PostTransaction et PostTransactionResult
2023-06-09 23:52:03 -04:00

97 lines
2.2 KiB
Go

package cmd
import (
"crypto/subtle"
"fmt"
"log"
"git.agecem.com/agecem/bottin-agenda/data"
"git.agecem.com/agecem/bottin-agenda/handlers"
bottindata "git.agecem.com/agecem/bottin/v5/data"
"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)
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(
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
e.POST("/v3/seed/", handlers.PostSeed)
e.GET("/v3/health/", handlers.GetHealth)
e.GET("/v3/transactions/", handlers.GetTransactions)
e.POST("/v3/transactions/", handlers.PostTransactions)
// Check bottin is ready
bottinHealthResponse, err := bottinConnection.GetHealth()
if err != nil {
log.Fatalf("[bottin] bottinConnection.GetHealth(): %s", err)
}
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(): %s", err)
} else {
log.Println("[bottin-agenda db] ok")
}
// Execution
e.Logger.Fatal(e.Start(fmt.Sprintf(":%d", apiPort)))
},
}
func init() {
rootCmd.AddCommand(apiCmd)
}