Files
go-cart-actor/cmd/backoffice/main.go
T
mats ad410d217c
Build and Publish / BuildAndDeployArm64 (push) Failing after 5s
Build and Publish / BuildAndDeployAmd64 (push) Has been cancelled
update cart
2026-06-17 14:16:25 +02:00

93 lines
2.5 KiB
Go

package main
import (
"context"
"errors"
"log"
"net/http"
"os"
"time"
"git.k6n.net/mats/go-cart-actor/pkg/backofficeadmin"
amqp "github.com/rabbitmq/amqp091-go"
)
func envOrDefault(key, def string) string {
if v := os.Getenv(key); v != "" {
return v
}
return def
}
func main() {
addr := envOrDefault("ADDR", ":8080")
amqpURL := os.Getenv("AMQP_URL")
app, err := backofficeadmin.New(backofficeadmin.Config{
DataDir: envOrDefault("CART_DIR", "data"),
CheckoutDataDir: envOrDefault("CHECKOUT_DIR", "checkout-data"),
RedisAddress: os.Getenv("REDIS_ADDRESS"),
RedisPassword: os.Getenv("REDIS_PASSWORD"),
})
if err != nil {
log.Fatalf("Error creating backoffice: %v", err)
}
mux := http.NewServeMux()
app.RegisterRoutes(mux)
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
mux.HandleFunc("/readyz", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
mux.HandleFunc("/livez", func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte("ok"))
})
// Global CORS middleware allowing all origins and handling preflight.
handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Access-Control-Allow-Origin", "*")
w.Header().Set("Access-Control-Allow-Methods", "GET, POST, PUT, PATCH, DELETE, OPTIONS")
w.Header().Set("Access-Control-Allow-Headers", "Content-Type, Authorization, X-Requested-With")
w.Header().Set("Access-Control-Expose-Headers", "*")
if r.Method == http.MethodOptions {
w.WriteHeader(http.StatusNoContent)
return
}
mux.ServeHTTP(w, r)
})
srv := &http.Server{
Addr: addr,
Handler: handler,
ReadTimeout: 15 * time.Second,
WriteTimeout: 30 * time.Second,
IdleTimeout: 60 * time.Second,
}
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
var conn *amqp.Connection
if amqpURL != "" {
conn, err = amqp.Dial(amqpURL)
if err != nil {
log.Fatalf("failed to connect to RabbitMQ: %v", err)
}
}
if err := app.Start(ctx, conn); err != nil {
log.Printf("AMQP listener disabled: %v", err)
} else if conn != nil {
log.Printf("AMQP listener connected")
}
log.Printf("backoffice HTTP listening on %s", addr)
if err := srv.ListenAndServe(); err != nil && !errors.Is(err, http.ErrServerClosed) {
log.Fatalf("http server error: %v", err)
}
}