Restructured - new game changer

This commit is contained in:
2025-10-26 19:20:59 +01:00
parent 2ac68aed86
commit 65105d6982
9 changed files with 49 additions and 61 deletions

View File

@@ -0,0 +1,37 @@
package postgresql
import (
"context"
"errors"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
)
func Connect(connStr string) (*pgxpool.Pool, error) {
pool, err := pgxpool.New(context.Background(), connStr)
if err != nil {
return nil, err
}
return pool, nil
}
func IsDuplicatedRow(err error) error {
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) && pgErr.Code == "23505" {
return errors.New("duplicated row found")
}
return nil
}
func NoRowsInQuerySet(err error) error {
if err == pgx.ErrNoRows {
return errors.New("no rows found")
}
return nil
}

104
client/rabbitmq/rabbitmq.go Normal file
View File

@@ -0,0 +1,104 @@
package rabbitmq
import (
"bytes"
"encoding/json"
"fmt"
"log"
amqp "github.com/rabbitmq/amqp091-go"
)
type Message map[string]interface{}
func Connect(url string) (*amqp.Connection, *amqp.Channel, error) {
conn, err := amqp.Dial(url)
if err != nil {
return nil, nil, err
}
ch, err := conn.Channel()
if err != nil {
log.Printf("Failed to open a channel: %v\n", err)
return nil, nil, err
}
return conn, ch, nil
}
func Close(conn *amqp.Connection) error {
return conn.Close()
}
func Serialize(msg any) (string, error) { // FIXME move to separate service
var b bytes.Buffer
encoder := json.NewEncoder(&b)
err := encoder.Encode(msg)
return b.String(), err
}
func Deserialize(b []byte) (Message, error) { // FIXME move to separate service
var msg Message
buf := bytes.NewBuffer(b)
decoder := json.NewDecoder(buf)
err := decoder.Decode(&msg)
return msg, err
}
func NewExchange(chn *amqp.Channel, name string) error {
err := chn.ExchangeDeclare(
name,
"direct", // type
true, // durable
false, // auto-deleted
false, // internal
false, // no-wait
nil, // arguments
)
if err != nil {
return err
}
return nil
}
func Publish(chn *amqp.Channel, name, routingKey string, msg any) error {
jsonData, err := Serialize(msg)
if err != nil {
return err
}
msgBody := fmt.Sprintf(`{"event":"%T","data":%s}`, msg, jsonData)
chn.Publish(
name, // exchange name
routingKey, // routing key
false, // mandatory
false, // immediate
amqp.Publishing{
ContentType: "application/json",
Body: []byte(msgBody),
},
)
return nil
}
func BindQueueToExchange(chn *amqp.Channel, queueName, exchName, routingKey string) error {
err := chn.QueueBind(
queueName, // queue name
routingKey, // routing key
exchName, // exchange name
false,
nil,
)
if err != nil {
log.Printf("Failed to bind a queue: %s\n", queueName)
return err
}
return nil
}