laresto-go-common

module
v1.0.1 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Dec 27, 2025 License: MIT

README ΒΆ

LaResto Go Common Library

Go Version Release Test Coverage License

Shared Go library for LaResto microservices ecosystem. Production-ready packages for building scalable restaurant management services.

🎯 Overview

LaResto Go Common provides 10 battle-tested packages that handle common microservice concerns:

  • πŸ”§ Foundation: Error handling, logging, validation
  • πŸ’Ύ Infrastructure: PostgreSQL, Redis, Kafka
  • 🌐 HTTP/API: HTTP client, JWT authentication, middleware
  • πŸ“Š Observability: Distributed tracing with OpenTelemetry

All packages integrate seamlessly with LaResto's Docker-based development infrastructure.

πŸ“¦ Packages

Foundation Packages
Package Description Coverage
errors Structured error handling with HTTP status mapping 92.3%
logger Structured JSON logging with zerolog 85.5%
validation Request validation with struct tags 69.1%
Infrastructure Packages
Package Description Coverage
database PostgreSQL connection management with sqlx 79.2%
cache Redis caching with JSON serialization 71.0%
kafka Event streaming producer/consumer 80.0%
HTTP/API Packages
Package Description Coverage
http HTTP client with retry logic 90.6%
jwt JWT token generation and validation 87.5%
middleware Gin HTTP middleware collection 96.4%
Observability Packages
Package Description Coverage
tracing Distributed tracing with OpenTelemetry 91.4%

Average Test Coverage: 85%+

πŸš€ Quick Start

Installation
go get github.com/LaRestoOU/laresto-go-common
Basic Usage
package main

import (
    "context"
    "time"

    "github.com/LaRestoOU/laresto-go-common/pkg/logger"
    "github.com/LaRestoOU/laresto-go-common/pkg/database"
    "github.com/LaRestoOU/laresto-go-common/pkg/cache"
    "github.com/gin-gonic/gin"
)

func main() {
    // Initialize logger
    log := logger.New(logger.Config{
        Level:       "info",
        ServiceName: "auth-service",
        Environment: "production",
    })

    // Connect to database
    db, err := database.Connect(database.Config{
        Host:     "localhost",
        Port:     5432,
        Database: "customer_db",
        User:     "laresto_app",
        Password: "password",
    }, log)
    if err != nil {
        log.Fatal("Database connection failed", err)
    }
    defer db.Close()

    // Connect to Redis
    cache, err := cache.NewRedis(cache.Config{
        Host:     "localhost",
        Port:     6379,
        Password: "redis_password",
        Prefix:   "auth:",
    }, log)
    if err != nil {
        log.Fatal("Redis connection failed", err)
    }
    defer cache.Close()

    // Setup HTTP server
    router := gin.New()
    router.GET("/health", func(c *gin.Context) {
        c.JSON(200, gin.H{"status": "healthy"})
    })

    log.Info("Server starting", "port", 8080)
    router.Run(":8080")
}

See examples/simple-service for a complete microservice example.

πŸ“š Documentation

Package Documentation

Each package includes comprehensive documentation:

  • README.md - Overview, features, usage examples
  • Code examples - Real-world usage patterns
  • Best practices - Do's and don'ts
  • iOS developer notes - Comparisons for developers transitioning from Swift

πŸ—οΈ Architecture

LaResto uses a microservices architecture with the following services:

β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚                     API Gateway (Traefik)                    β”‚
β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
               β”‚
    β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
    β–Ό                     β–Ό              β–Ό              β–Ό
β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”         β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”   β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
β”‚  Auth   β”‚         β”‚ Customer β”‚   β”‚  Order  β”‚   β”‚ Payment  β”‚
β”‚ Service │◄───────── Service  β”‚   β”‚ Service β”‚   β”‚ Service  β”‚
β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜         β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜   β””β”€β”€β”€β”€β”€β”¬β”€β”€β”€β”€β”˜
     β”‚                    β”‚             β”‚              β”‚
     β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                          β”‚
                    β”Œβ”€β”€β”€β”€β”€β”΄β”€β”€β”€β”€β”€β”
                    β–Ό           β–Ό
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”  β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚PostgreSQLβ”‚  β”‚ Redis  β”‚
            β”‚(11 DBs)  β”‚  β”‚        β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜  β””β”€β”€β”€β”€β”€β”€β”€β”€β”˜
                    β”‚
                    β–Ό
            β”Œβ”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”
            β”‚    Kafka     β”‚
            β”‚(Event Stream)β”‚
            β””β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”€β”˜
Infrastructure Stack
  • Database: PostgreSQL with database-per-service pattern
  • Cache: Redis for sessions, rate limiting, caching
  • Messaging: Apache Kafka for event-driven communication
  • Observability: Jaeger (tracing), Prometheus (metrics), Grafana (dashboards)
  • Gateway: Traefik for routing and load balancing

See docs/ARCHITECTURE.md for detailed architecture documentation.

πŸ› οΈ Development

Prerequisites
  • Go 1.21 or higher
  • Docker & Docker Compose
  • Git
Local Development Setup
  1. Clone the repository
git clone https://github.com/LaRestoOU/laresto-go-common.git
cd laresto-go-common
  1. Install dependencies
go mod download
  1. Start infrastructure (from laresto-docker-compose)
cd ../laresto-docker-compose
docker-compose up -d
  1. Run tests
go test ./...
  1. Run with coverage
go test -cover ./...
Running Integration Tests

Integration tests require running infrastructure:

# Start all services
cd ../laresto-docker-compose
docker-compose up -d

# Run all tests
cd ../laresto-go-common
go test -v ./...

# Run specific package tests
go test -v ./pkg/database/
go test -v ./pkg/cache/
go test -v ./pkg/kafka/
Code Quality
# Format code
go fmt ./...

# Lint
golangci-lint run

# Check for issues
go vet ./...

🎯 Usage Examples

Error Handling
import "github.com/LaRestoOU/laresto-go-common/pkg/errors"

func GetUser(id string) (*User, error) {
    user, err := db.FindUser(id)
    if err != nil {
        return nil, errors.WrapDB(err)
    }
    
    if user == nil {
        return nil, errors.ErrNotFound
    }
    
    return user, nil
}
Logging
import "github.com/LaRestoOU/laresto-go-common/pkg/logger"

log := logger.New(logger.Config{
    Level:       "info",
    ServiceName: "auth-service",
})

log.Info("User logged in", "user_id", userID, "ip", ipAddress)
log.Error("Database query failed", err, "query", query)
Validation
import "github.com/LaRestoOU/laresto-go-common/pkg/validation"

type RegisterRequest struct {
    Email    string `validate:"required,email"`
    Password string `validate:"required,strong_password"`
    Age      int    `validate:"required,gte=18"`
}

v := validation.New()
if err := v.Validate(req); err != nil {
    return err // Returns errors.ErrValidation with details
}
Database Operations
import "github.com/LaRestoOU/laresto-go-common/pkg/database"

db, _ := database.Connect(config, log)

// Query single row
var user User
err := db.GetContext(ctx, &user, "SELECT * FROM users WHERE id = $1", userID)

// Transaction
err = db.Transaction(ctx, func(tx *sqlx.Tx) error {
    _, err := tx.Exec("INSERT INTO orders ...")
    _, err = tx.Exec("UPDATE inventory ...")
    return err
})
Caching
import "github.com/LaRestoOU/laresto-go-common/pkg/cache"

cache, _ := cache.NewRedis(config, log)

// Set with TTL
cache.Set(ctx, "user:123", user, 1*time.Hour)

// Get
var user User
err := cache.Get(ctx, "user:123", &user)
Event Publishing
import "github.com/LaRestoOU/laresto-go-common/pkg/kafka"

producer, _ := kafka.NewProducer(config, log)

event := UserRegisteredEvent{
    UserID: "123",
    Email:  "user@example.com",
}

producer.Publish(ctx, "user.registered", userID, event)
HTTP Client
import "github.com/LaRestoOU/laresto-go-common/pkg/http"

client := http.NewClient(config, log)

resp, err := client.Get(ctx, "https://api.example.com/users/123", headers)
var user User
resp.JSON(&user)
JWT Authentication
import "github.com/LaRestoOU/laresto-go-common/pkg/jwt"

tm, _ := jwt.NewTokenManager(config)

// Generate tokens
tokens, err := tm.GenerateTokenPair(userID, email, role)

// Validate
claims, err := tm.ValidateAccessToken(accessToken)
Middleware
import "github.com/LaRestoOU/laresto-go-common/pkg/middleware"

router := gin.New()
router.Use(middleware.RequestID())
router.Use(middleware.Logger(log))
router.Use(middleware.Recovery(log))
router.Use(middleware.CORS([]string{"https://app.laresto.com"}))
Distributed Tracing
import "github.com/LaRestoOU/laresto-go-common/pkg/tracing"

provider, _ := tracing.NewProvider(config, log)
defer provider.Shutdown(ctx)

ctx, span := tracing.StartSpan(ctx, "auth-service", "process-login")
defer span.End()

tracing.SetAttributes(ctx, tracing.UserID.String(userID))

πŸ§ͺ Testing

Test Coverage
# All packages
go test -cover ./...

# Specific package with details
go test -v -coverprofile=coverage.out ./pkg/database/
go tool cover -html=coverage.out
Integration Tests

Integration tests are skipped by default. Run with infrastructure:

# Start infrastructure
cd ../laresto-docker-compose
docker-compose up -d

# Run integration tests
cd ../laresto-go-common
go test -v ./pkg/database/
go test -v ./pkg/cache/
go test -v ./pkg/kafka/
Benchmark Tests
go test -bench=. ./pkg/logger/
go test -bench=. ./pkg/cache/

πŸ“ˆ Performance

  • Logger: ~50ns per log line (zero allocation)
  • Cache: <1ms for get/set operations
  • Database: Connection pooling for optimal performance
  • HTTP Client: Automatic retry with backoff
  • Kafka: Batch processing (100 messages or 1s)

πŸ”’ Security

  • JWT: HMAC-SHA256 signing with separate secrets
  • Passwords: Never logged or cached
  • TLS: Configurable for all connections
  • Rate Limiting: IP-based protection
  • SQL Injection: Parameterized queries only

🀝 Contributing

We welcome contributions! Please see our Contributing Guide.

  1. Fork the repository
  2. Create your feature branch (git checkout -b feature/amazing-feature)
  3. Write tests for your changes
  4. Ensure tests pass (go test ./...)
  5. Commit your changes (git commit -m 'Add amazing feature')
  6. Push to the branch (git push origin feature/amazing-feature)
  7. Open a Pull Request

πŸ“ Changelog

See CHANGELOG.md for version history.

πŸ“„ License

This project is licensed under the MIT License - see LICENSE file for details.

πŸ™ Acknowledgments

  • Built for LaResto - Restaurant Management Platform
  • Developed by LaRestoOU
  • Inspired by industry best practices and Go community standards

πŸ“ž Support


Built with ❀️ in Estonia πŸ‡ͺπŸ‡ͺ

Directories ΒΆ

Path Synopsis
examples
simple-service command
pkg
cache
Package cache provides Redis caching functionality with automatic serialization.
Package cache provides Redis caching functionality with automatic serialization.
database
Package database provides PostgreSQL connection management using sqlx.
Package database provides PostgreSQL connection management using sqlx.
errors
Package errors provides standardized error handling for LaResto microservices.
Package errors provides standardized error handling for LaResto microservices.
http
Package http provides HTTP client functionality with retry logic, timeouts, and logging.
Package http provides HTTP client functionality with retry logic, timeouts, and logging.
jwt
Package jwt provides JWT token generation and validation for LaResto authentication.
Package jwt provides JWT token generation and validation for LaResto authentication.
kafka
Package kafka provides event streaming with Kafka for LaResto microservices.
Package kafka provides event streaming with Kafka for LaResto microservices.
logger
Package logger provides structured logging with zerolog for LaResto microservices.
Package logger provides structured logging with zerolog for LaResto microservices.
middleware
Package middleware provides HTTP middleware for Gin framework.
Package middleware provides HTTP middleware for Gin framework.
tracing
Package tracing provides distributed tracing with OpenTelemetry.
Package tracing provides distributed tracing with OpenTelemetry.
validation
Package validation provides request validation using struct tags.
Package validation provides request validation using struct tags.

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL