feat(api): wire server configuration and dependencies

This commit is contained in:
2026-09-21 14:15:30 +03:30
parent 5dbfe0a12f
commit 3f29a5ec5f
6 changed files with 225 additions and 7 deletions

View File

@@ -1,18 +1,103 @@
package main
import (
"context"
"encoding/json"
"log"
"errors"
"fmt"
"log/slog"
"net/http"
"os"
"time"
"card-to-iban/internal/httpapi"
"card-to-iban/internal/repository"
"card-to-iban/internal/service"
"card-to-iban/internal/storage"
"card-to-iban/internal/zarinhub"
"github.com/joho/godotenv"
)
func main() {
http.HandleFunc("/health", healthHandler)
logger := slog.New(
slog.NewJSONHandler(os.Stdout, nil),
)
log.Println("server listening on http://localhost:8080")
if err := run(logger); err != nil {
logger.Error("server stopped", "error", err)
os.Exit(1)
}
}
if err := http.ListenAndServe(":8080", nil); err != nil {
log.Fatal(err)
func run(logger *slog.Logger) error {
loadLocalEnvironment()
config, err := loadConfig()
if err != nil {
return fmt.Errorf("load configuration: %w", err)
}
db, err := storage.OpenSQLite(config.DatabasePath)
if err != nil {
return err
}
migrationContext, cancelMigration := context.WithTimeout(
context.Background(),
5*time.Second,
)
defer cancelMigration()
if err := storage.Migrate(migrationContext, db); err != nil {
if closeErr := db.Close(); closeErr != nil {
return errors.Join(err, closeErr)
}
return err
}
zarinHubClient := zarinhub.NewClient(
&http.Client{Timeout: config.ZarinHubTimeout},
config.ZarinHubEndpoint,
config.ZarinHubToken,
)
cardService := service.NewCardService(zarinHubClient)
auditRepository := repository.NewAuditRepository(db)
handler := httpapi.NewHandler(
cardService,
auditRepository,
logger,
)
mux := http.NewServeMux()
mux.HandleFunc("/health", healthHandler)
mux.HandleFunc("/api/v1/card-to-iban", handler.Convert)
server := &http.Server{
Addr: config.ServerAddr,
Handler: httpapi.AllowOrigin(
config.FrontendOrigin,
mux,
),
ReadHeaderTimeout: 5 * time.Second,
ReadTimeout: 10 * time.Second,
WriteTimeout: 15 * time.Second,
IdleTimeout: 60 * time.Second,
}
logger.Info("server listening", "address", config.ServerAddr)
serverErr := server.ListenAndServe()
closeErr := db.Close()
return errors.Join(serverErr, closeErr)
}
func loadLocalEnvironment() {
for _, path := range []string{".env", "../.env"} {
if err := godotenv.Load(path); err == nil {
return
}
}
}
@@ -29,6 +114,10 @@ func healthHandler(w http.ResponseWriter, r *http.Request) {
}
if err := json.NewEncoder(w).Encode(response); err != nil {
log.Println("failed to encode health response:", err)
slog.ErrorContext(
r.Context(),
"health response encoding failed",
"error", err,
)
}
}