Add executable
This commit is contained in:
parent
4c67f5844b
commit
c37e2a312a
70
cmd/converter/main.go
Normal file
70
cmd/converter/main.go
Normal file
|
|
@ -0,0 +1,70 @@
|
|||
package main
|
||||
|
||||
import (
|
||||
"context"
|
||||
"converter/app"
|
||||
"converter/domain"
|
||||
"converter/infrastructure/coinmarketcap"
|
||||
"fmt"
|
||||
"os"
|
||||
"os/signal"
|
||||
"syscall"
|
||||
"time"
|
||||
)
|
||||
|
||||
const (
|
||||
expectedArgs = 4 // program name + 3 arguments
|
||||
apiKeyEnvVar = "CMC_API_KEY"
|
||||
)
|
||||
|
||||
func main() {
|
||||
// Check command line arguments
|
||||
if len(os.Args) != expectedArgs {
|
||||
fmt.Fprintf(os.Stderr, "Usage: %s <amount> <from_currency> <to_currency>\n", os.Args[0])
|
||||
fmt.Fprintf(os.Stderr, "Example: %s 100.50 USD BTC\n", os.Args[0])
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Parse arguments
|
||||
amount := os.Args[1]
|
||||
fromCurrency := os.Args[2]
|
||||
toCurrency := os.Args[3]
|
||||
|
||||
// Get API key from environment
|
||||
apiKey := os.Getenv(apiKeyEnvVar)
|
||||
if apiKey == "" {
|
||||
fmt.Fprintf(os.Stderr, "Error: %s environment variable is required\n", apiKeyEnvVar)
|
||||
fmt.Fprintf(os.Stderr, "Please set your CoinMarketCap API key:\n")
|
||||
fmt.Fprintf(os.Stderr, "export %s=your_api_key_here\n", apiKeyEnvVar)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Initialize dependencies
|
||||
client := coinmarketcap.NewClient(apiKey)
|
||||
converter := domain.NewCurrencyConverter()
|
||||
useCase := app.NewConvertCurrencyUseCase(client, converter)
|
||||
|
||||
// Create context with timeout and signal handling
|
||||
ctx, cancel := context.WithTimeout(context.Background(), 30*time.Second)
|
||||
defer cancel()
|
||||
|
||||
// Set up graceful shutdown on interrupt signals
|
||||
sigChan := make(chan os.Signal, 1)
|
||||
signal.Notify(sigChan, syscall.SIGINT, syscall.SIGTERM)
|
||||
|
||||
go func() {
|
||||
<-sigChan
|
||||
fmt.Fprintf(os.Stderr, "\nReceived interrupt signal, shutting down...\n")
|
||||
cancel()
|
||||
}()
|
||||
|
||||
// Execute conversion
|
||||
result, err := useCase.Execute(ctx, amount, fromCurrency, toCurrency)
|
||||
if err != nil {
|
||||
fmt.Fprintf(os.Stderr, "Error: %v\n", err)
|
||||
os.Exit(1)
|
||||
}
|
||||
|
||||
// Output result
|
||||
fmt.Printf("%s %s\n", result.Amount.StringFixed(8), result.Currency.Code)
|
||||
}
|
||||
Loading…
Reference in a new issue