65 lines
1.5 KiB
Go
65 lines
1.5 KiB
Go
/*
|
|
Copyright © 2023 AGECEM & Victor Lacasse-Beaudoin
|
|
*/
|
|
package cmd
|
|
|
|
import (
|
|
"crypto/subtle"
|
|
"fmt"
|
|
"log"
|
|
|
|
"git.agecem.com/agecem/bottin-ag/apihandler"
|
|
"git.agecem.com/agecem/bottin-ag/config"
|
|
"git.agecem.com/agecem/bottin-ag/dbclient"
|
|
bottindata "git.agecem.com/agecem/bottin/v5/data"
|
|
"github.com/labstack/echo/v4"
|
|
"github.com/labstack/echo/v4/middleware"
|
|
"github.com/spf13/cobra"
|
|
)
|
|
|
|
// apiCmd represents the api command
|
|
var apiCmd = &cobra.Command{
|
|
Use: "api",
|
|
Short: "Start the API server",
|
|
Run: func(cmd *cobra.Command, args []string) {
|
|
cfg, err := config.UnmarshalConfig()
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
e := echo.New()
|
|
|
|
e.Pre(middleware.AddTrailingSlash())
|
|
|
|
if cfg.API.Key != "" {
|
|
e.Use(middleware.KeyAuth(func(key string, c echo.Context) (bool, error) {
|
|
return subtle.ConstantTimeCompare([]byte(key), []byte(cfg.API.Key)) == 1, nil
|
|
}))
|
|
log.Println("API server is using an API key")
|
|
}
|
|
|
|
v0 := e.Group("/v0")
|
|
|
|
bottinApiClient := bottindata.NewApiClient(cfg.Bottin.API.Key, cfg.Bottin.API.Host, cfg.Bottin.API.Protocol, cfg.Bottin.API.Port)
|
|
|
|
dbClient, err := dbclient.New(cfg.DB.Host, cfg.DB.Database, cfg.DB.User, cfg.DB.Password, cfg.DB.Port, cfg.DB.UseSSL)
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer dbClient.DB.Close()
|
|
|
|
handler := apihandler.New(bottinApiClient, dbClient)
|
|
|
|
if err := handler.DBClient.CreateTablesIfNotExist(); err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
|
|
apihandler.DeclareRoutes(v0, &handler)
|
|
|
|
e.Start(fmt.Sprintf(":%d", cfg.API.Port))
|
|
},
|
|
}
|
|
|
|
func init() {
|
|
rootCmd.AddCommand(apiCmd)
|
|
}
|