56 lines
1.6 KiB
Go
56 lines
1.6 KiB
Go
// 2026-03-21 — go-counter-atomic: считает вызовы через atomic в памяти + пишет в PG.
|
|
// Тестирует: in-memory state между вызовами (Go pod остаётся живым), + PG INSERT на каждый вызов.
|
|
package handler
|
|
|
|
import (
|
|
"context"
|
|
"fmt"
|
|
"os"
|
|
"sync/atomic"
|
|
"time"
|
|
|
|
"github.com/jackc/pgx/v5/pgxpool"
|
|
)
|
|
|
|
// invocations считается между вызовами (пока pod жив).
|
|
var invocations int64
|
|
|
|
// Handle записывает факт вызова в PG и возвращает накопленный счётчик.
|
|
func Handle(event map[string]interface{}) interface{} {
|
|
n := atomic.AddInt64(&invocations, 1)
|
|
|
|
dsn := fmt.Sprintf(
|
|
"host=%s port=%s dbname=%s user=%s password=%s sslmode=%s",
|
|
os.Getenv("PGHOST"), envOrDefault("PGPORT", "5432"),
|
|
os.Getenv("PGDATABASE"), os.Getenv("PGUSER"),
|
|
os.Getenv("PGPASSWORD"), envOrDefault("PGSSLMODE", "require"),
|
|
)
|
|
pool, err := pgxpool.New(context.Background(), dsn)
|
|
if err != nil {
|
|
return map[string]interface{}{"invocation_n": n, "error": err.Error()}
|
|
}
|
|
defer pool.Close()
|
|
|
|
title := fmt.Sprintf("go-counter-invoke-%d-%d", n, time.Now().UnixMilli())
|
|
var id int64
|
|
err = pool.QueryRow(context.Background(),
|
|
"INSERT INTO terraform_demo_table (title) VALUES ($1) RETURNING id", title,
|
|
).Scan(&id)
|
|
if err != nil {
|
|
return map[string]interface{}{"invocation_n": n, "error": err.Error()}
|
|
}
|
|
|
|
return map[string]interface{}{
|
|
"invocation_n": n,
|
|
"inserted_id": id,
|
|
"title": title,
|
|
}
|
|
}
|
|
|
|
func envOrDefault(key, def string) string {
|
|
if v := os.Getenv(key); v != "" {
|
|
return v
|
|
}
|
|
return def
|
|
}
|