feat: Config from env

This commit is contained in:
2024-12-11 18:30:46 +01:00
parent 715eb8e1cb
commit 4faf76a073
10 changed files with 178 additions and 31 deletions

59
main.go
View File

@@ -3,24 +3,23 @@ package main
import (
"crypto/sha256"
"crypto/subtle"
"flag"
"log"
"git.odit.services/lfk/document-server/docs" // Correct import path for docs
"git.odit.services/lfk/document-server/handlers"
"git.odit.services/lfk/document-server/models"
"github.com/gofiber/fiber/v2"
"github.com/gofiber/fiber/v2/middleware/keyauth"
"github.com/gofiber/swagger"
"github.com/spf13/viper"
)
var (
port = flag.String("port", ":3000", "Port to listen on")
prod = flag.Bool("prod", false, "Enable prefork in Production")
apiKey = flag.String("apikey", "lfk", "API key for incoming authentication")
config *models.Config
)
func validateAPIKey(c *fiber.Ctx, key string) (bool, error) {
hashedAPIKey := sha256.Sum256([]byte(*apiKey))
hashedAPIKey := sha256.Sum256([]byte(config.APIKey))
hashedKey := sha256.Sum256([]byte(key))
if subtle.ConstantTimeCompare(hashedAPIKey[:], hashedKey[:]) == 1 {
@@ -29,15 +28,49 @@ func validateAPIKey(c *fiber.Ctx, key string) (bool, error) {
return false, keyauth.ErrMissingOrMalformedAPIKey
}
func loadEnv() error {
viper.SetDefault("PORT", "3000")
viper.SetDefault("CARD_BARCODEFORMAT", "ean13")
viper.SetDefault("CARD_BARCODEPREFIX", "")
viper.SetDefault("SPONSORING_BARCODEFORMAT", "code128")
viper.SetDefault("SPONSORING_BARCODEPREFIX", "")
// Load .env file
viper.SetConfigFile(".env")
// Load environment variables
viper.AutomaticEnv()
err := viper.ReadInConfig()
if err != nil {
return err
}
// Unmarshal the config from file and env into the config struct
err = viper.Unmarshal(&config)
if err != nil {
return err
}
return nil
}
// @title LfK Document Server API
// @description This is the API documentation for the LfK Document Server - a tool for pdf generation.
func main() {
// Parse command-line flags
flag.Parse()
err := loadEnv()
if err != nil {
log.Fatal(err)
}
handler := handlers.DefaultHandler{
Config: config,
}
// Create a new Fiber instance
app := fiber.New(fiber.Config{
Prefork: *prod,
Prefork: config.Prod,
})
// Swagger documentation route
@@ -52,12 +85,12 @@ func main() {
v1.Get("/", func(c *fiber.Ctx) error {
return c.SendString("Hello, World!")
})
v1.Post("/contracts", handlers.GenerateContract)
v1.Post("/cards", handlers.GenerateCard)
v1.Post("/certificates", handlers.GenerateCertificate)
v1.Post("/contracts", handler.GenerateContract)
v1.Post("/cards", handler.GenerateCard)
v1.Post("/certificates", handler.GenerateCertificate)
app.Use(handlers.NotFoundHandler)
app.Use(handler.NotFoundHandler)
docs.SwaggerInfo.BasePath = "/"
log.Fatal(app.Listen(*port))
log.Fatal(app.Listen("0.0.0.0:" + config.Port))
}