LaResto Go Common Library

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
Quick Links
ποΈ 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
- Clone the repository
git clone https://github.com/LaRestoOU/laresto-go-common.git
cd laresto-go-common
- Install dependencies
go mod download
- Start infrastructure (from laresto-docker-compose)
cd ../laresto-docker-compose
docker-compose up -d
- Run tests
go test ./...
- 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/
- 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.
- Fork the repository
- Create your feature branch (
git checkout -b feature/amazing-feature)
- Write tests for your changes
- Ensure tests pass (
go test ./...)
- Commit your changes (
git commit -m 'Add amazing feature')
- Push to the branch (
git push origin feature/amazing-feature)
- 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 πͺπͺ