Architecture
Backend Architecture
Detailed architecture of the Go backend — routing, middleware, handlers, and services.
Backend Architecture
The BAP backend is built with Go, using the Chi router and modern Go patterns.
Technology Stack
| Component | Technology |
|---|---|
| Language | Go 1.26 |
| Router | Chi v5 |
| Database | SQLite (dev) / PostgreSQL (prod) |
| ORM | GORM |
| Migrations | golang-migrate/migrate/v4 |
| Authentication | JWT |
| Encryption | AES-256-GCM, Ed25519, Shamir's SSS |
| Config | kelseyhightower/envconfig |
| Logging | go.uber.org/zap |
Project Structure
api/
├── cmd/
│ └── api/
│ └── main.go # Entry point
├── internal/
│ ├── handler/ # HTTP handlers
│ │ ├── auth.go
│ │ ├── host.go
│ │ ├── survivor.go
│ │ ├── connector.go
│ │ ├── storage.go
│ │ ├── will.go
│ │ ├── liveness.go
│ │ └── transfer.go
│ ├── middleware/ # HTTP middleware
│ │ ├── auth.go
│ │ ├── ratelimit.go
│ │ └── cors.go
│ ├── repository/ # Database access
│ │ ├── host.go
│ │ ├── survivor.go
│ │ ├── will.go
│ │ ├── connector.go
│ │ └── storage.go
│ ├── crypto/ # Encryption
│ │ ├── crypto.go
│ │ ├── sss.go
│ │ └── keyderivation.go
│ ├── connector/ # Notification providers
│ │ ├── email.go
│ │ ├── sms.go
│ │ ├── whatsapp.go
│ │ └── telegram.go
│ ├── storage/ # Storage providers
│ │ ├── gdrive.go
│ │ ├── dropbox.go
│ │ ├── s3.go
│ │ └── sftp.go
│ ├── scheduler/ # Background jobs
│ │ └── liveness.go
│ └── dbutil/ # Database utilities
│ └── migrations/
└── migrations/ # SQL migrationsHTTP Layer
Router (Chi)
The Chi router provides:
- RESTful routing
- Middleware chaining
- URL parameters
- Request context
Routes
/api
├── /auth
│ ├── POST /register
│ ├── POST /login
│ ├── POST /logout
│ └── POST /refresh
│
├── /host
│ ├── GET /profile
│ ├── PUT /profile
│ └── GET /settings
│
├── /connectors
│ ├── GET /
│ ├── POST /
│ ├── PUT /:id
│ ├── DELETE /:id
│ └── POST /:id/test
│
├── /storages
│ ├── GET /
│ ├── POST /
│ ├── POST /connect
│ ├── GET /oauth/callback
│ ├── GET /:id/browse
│ └── DELETE /:id
│
├── /survivors
│ ├── GET /
│ ├── POST /
│ ├── PUT /:id
│ ├── DELETE /:id
│ └── PUT /minimum-count
│
├── /will
│ ├── GET /status
│ ├── POST /upload
│ └── POST /encrypt
│
├── /liveness
│ ├── POST /alive
│ └── GET /history
│
├── /transfer
│ ├── POST /initiate
│ ├── POST /cancel
│ └── GET /status
│
├── /survivor-auth
│ ├── POST /select
│ ├── POST /verify-otp
│ └── GET /will-access
│
└── /health
└── GET /Middleware
Authentication Middleware
Validates JWT tokens and extracts user context:
func AuthMiddleware(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
token := extractToken(r)
claims, err := validateToken(token)
if err != nil {
http.Error(w, "Unauthorized", http.StatusUnauthorized)
return
}
ctx := context.WithValue(r.Context(), "host_id", claims.HostID)
next.ServeHTTP(w, r.WithContext(ctx))
})
}Rate Limiting
Per-endpoint rate limits:
- Auth endpoints: 10/15min
- OTP: 5/hour per survivor
- General: 100/minute
CORS
Configurable allowed origins:
cors.Handler(cors.Options{
AllowedOrigins: []string{"https://yourdomain.com"},
AllowedMethods: []string{"GET", "POST", "PUT", "DELETE"},
AllowedHeaders: []string{"Authorization", "Content-Type"},
})Security Headers
- Content-Security-Policy
- X-Frame-Options: DENY
- X-Content-Type-Options: nosniff
- Strict-Transport-Security
Handlers
Handler Pattern
Each handler follows a consistent pattern:
func (h *Handler) HandleSomething(w http.ResponseWriter, r *http.Request) {
// 1. Extract and validate input
// 2. Call repository/service
// 3. Return response or error
}Error Handling
Standardized error format:
{
"error": {
"code": "VALIDATION_ERROR",
"message": "Human-readable description",
"details": [
{ "field": "email", "message": "Invalid email format" }
]
}
}Services
Crypto Service
Handles all encryption operations:
- AES-256-GCM encryption/decryption
- Key derivation (HKDF)
- Shamir's Secret Sharing split/combine
Connector Manager
Manages notification delivery:
- Email (SMTP — any provider)
- SMS (Twilio)
- WhatsApp (Meta Cloud API)
- Telegram (Bot API)
Storage Manager
Abstracts storage backends:
- Google Drive (OAuth)
- Dropbox (OAuth)
- AWS S3
- SFTP
Scheduler
Background job runner (polling-based, 30s interval goroutine in main.go):
- Liveness check executor
- Transfer deadline enforcement
- OAuth token refresh
- Storage permission sync
Database Layer
Repositories
Data access through repositories:
type HostRepository interface {
Create(host *Host) error
GetByID(id uuid.UUID) (*Host, error)
GetByEmail(email string) (*Host, error)
Update(host *Host) error
}Migrations
SQL migrations for schema:
- Versioned migrations
- Up/down pairs
- Automatic migration on startup
Configuration
Environment Variables
type Config struct {
Port int
DBType string
DatabaseURL string
JWTSecret string
MasterKey string
CORSOrigins string
}Validation
Uses kelseyhightower/envconfig for environment variable parsing.
Testing
Unit Tests
- Handler tests with mock repositories
- Crypto service tests
- Utility function tests
Integration Tests
- Database tests with testcontainers
- API endpoint tests
Performance
Optimization Techniques
- GORM connection pooling
- Streaming for large files
- Encrypted-at-rest repository layer for sensitive fields
Next Steps
- Frontend Architecture — Next.js details
- Database Schema — Schema design
- Encryption — Cryptographic details