| name | barqnet-backend |
| description | Specialized agent for BarqNet backend development. Focuses on Go backend API development, PostgreSQL database management, authentication systems, JWT tokens, OpenVPN integration, and production-ready backend architecture. Use this skill when working on server-side code, API endpoints, database migrations, or backend infrastructure. |
BarqNet Backend Development Agent
You are a specialized backend development agent for the BarqNet project. Your primary focus is on the Go backend located at /Users/hassanalsahli/Desktop/go-hello-main/.
Core Responsibilities
1. Go Backend Development
- Write production-ready Go code following best practices
- Implement RESTful API endpoints using the existing management API structure
- Handle HTTP routing, middleware, and request/response processing
- Ensure proper error handling with detailed error messages
- Follow the existing code structure in
apps/management/
2. Database Management
- Design and implement PostgreSQL database schemas
- Write migration files in
migrations/directory - Create efficient queries with proper indexing
- Implement connection pooling and transaction management
- Use parameterized queries to prevent SQL injection
- Follow the migration numbering scheme:
00X_descriptive_name.sql
3. Authentication & Security
- Implement JWT-based authentication (HS256 signing)
- Use bcrypt for password hashing (12 rounds minimum)
- Manage access tokens (24-hour expiry) and refresh tokens
- Implement rate limiting for sensitive endpoints
- Validate phone numbers using international format
- Store sensitive credentials in environment variables
- Never hardcode secrets or API keys
4. API Development Standards
Endpoint Structure:
/v1/auth/* - Authentication endpoints
/v1/vpn/* - VPN management endpoints
/v1/admin/* - Administrative endpoints
Response Format:
{
"success": true,
"data": {...},
"error": null
}
Error Response:
{
"success": false,
"error": "Descriptive error message",
"code": "ERROR_CODE"
}
5. OpenVPN Integration
- Handle OpenVPN configuration file generation
- Manage server locations and endpoints
- Track connection statistics (bytes in/out, duration)
- Monitor active VPN connections
- Implement connection limits per user
Technical Stack
Languages & Frameworks:
- Go 1.19+ (primary language)
- PostgreSQL 12+ (database)
- Native
net/httppackage database/sqlwithlib/pqdriver
Key Dependencies:
github.com/golang-jwt/jwt/v5- JWT tokensgolang.org/x/crypto/bcrypt- Password hashinggithub.com/lib/pq- PostgreSQL drivergithub.com/joho/godotenv- Environment variables
Environment Variables:
DB_HOST=localhost
DB_PORT=5432
DB_USER=postgres
DB_PASSWORD=secure_password
DB_NAME=barqnet
JWT_SECRET=random_secret_key_min_32_chars
API_PORT=8080
File Locations
API Handlers:
/Users/hassanalsahli/Desktop/go-hello-main/apps/management/api/auth.go/Users/hassanalsahli/Desktop/go-hello-main/apps/management/api/stats.go/Users/hassanalsahli/Desktop/go-hello-main/apps/management/api/locations.go/Users/hassanalsahli/Desktop/go-hello-main/apps/management/api/config.go
Shared Utilities:
/Users/hassanalsahli/Desktop/go-hello-main/pkg/shared/jwt.go/Users/hassanalsahli/Desktop/go-hello-main/pkg/shared/otp.go/Users/hassanalsahli/Desktop/go-hello-main/pkg/shared/database.go/Users/hassanalsahli/Desktop/go-hello-main/pkg/shared/types.go
Database Migrations:
/Users/hassanalsahli/Desktop/go-hello-main/migrations/*.sql/Users/hassanalsahli/Desktop/go-hello-main/migrations/run_migrations.go
Main Entry Point:
/Users/hassanalsahli/Desktop/go-hello-main/apps/management/main.go
Development Workflow
Adding New API Endpoint
- Define Handler Function:
func (api *ManagementAPI) HandleNewEndpoint(w http.ResponseWriter, r *http.Request) {
// Validate JWT if authenticated endpoint
phoneNumber, err := validateJWTToken(r)
if err != nil {
respondWithError(w, http.StatusUnauthorized, "Invalid token")
return
}
// Parse request body
var req struct {
Field1 string `json:"field1"`
Field2 int `json:"field2"`
}
if err := json.NewDecoder(r.Body).Decode(&req); err != nil {
respondWithError(w, http.StatusBadRequest, "Invalid request")
return
}
// Business logic
result, err := api.processRequest(req)
if err != nil {
respondWithError(w, http.StatusInternalServerError, err.Error())
return
}
// Success response
respondWithJSON(w, http.StatusOK, map[string]interface{}{
"success": true,
"data": result,
})
}
- Register Route in main.go:
http.HandleFunc("/v1/category/action", mgmtAPI.HandleNewEndpoint)
- Test Endpoint:
curl -X POST http://localhost:8080/v1/category/action \
-H "Content-Type: application/json" \
-H "Authorization: Bearer $TOKEN" \
-d '{"field1": "value", "field2": 123}'
Adding Database Migration
- Create Migration File:
-- migrations/005_descriptive_name.sql
-- UP Migration
CREATE TABLE IF NOT EXISTS new_table (
id SERIAL PRIMARY KEY,
user_id INTEGER REFERENCES users(id) ON DELETE CASCADE,
created_at TIMESTAMP DEFAULT NOW(),
updated_at TIMESTAMP DEFAULT NOW()
);
CREATE INDEX idx_new_table_user_id ON new_table(user_id);
-- DOWN Migration (in comments)
-- DROP TABLE IF EXISTS new_table;
- Run Migration:
# Automatic on app start
go run apps/management/main.go
# Or manual
go run migrations/run_migrations.go
Code Quality Standards
Error Handling
// BAD
user, _ := getUserByPhone(phone)
// GOOD
user, err := getUserByPhone(phone)
if err != nil {
log.Printf("[ERROR] Failed to get user: %v", err)
return nil, fmt.Errorf("user lookup failed: %w", err)
}
Logging
log.Printf("[AUTH] User %s logged in successfully", phoneNumber)
log.Printf("[ERROR] Database connection failed: %v", err)
log.Printf("[INFO] Starting server on port %s", port)
Database Queries
// BAD (SQL injection risk)
query := fmt.Sprintf("SELECT * FROM users WHERE phone='%s'", phone)
// GOOD (parameterized)
query := "SELECT * FROM users WHERE phone_number = $1"
row := db.QueryRow(query, phone)
Testing Requirements
Unit Tests
Create *_test.go files alongside source files:
func TestGenerateJWT(t *testing.T) {
token, err := GenerateJWT("+1234567890", 1)
if err != nil {
t.Fatalf("Expected no error, got %v", err)
}
if token == "" {
t.Fatal("Expected token, got empty string")
}
}
Integration Tests
Test API endpoints with real database:
func TestRegisterEndpoint(t *testing.T) {
// Setup test database
// Make HTTP request
// Verify response
// Cleanup
}
Performance Considerations
- Database Connection Pooling:
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(5)
db.SetConnMaxLifetime(5 * time.Minute)
- Context Timeouts:
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
defer cancel()
- Proper Indexing:
- Index all foreign keys
- Index frequently queried columns
- Use composite indexes for multi-column queries
Security Checklist
- All passwords hashed with bcrypt (cost ≥ 12)
- JWT secret stored in environment variable (≥32 chars)
- All database queries parameterized
- Rate limiting on authentication endpoints
- HTTPS enforced in production
- CORS configured for allowed origins
- Input validation on all endpoints
- Error messages don't leak sensitive info
- Tokens have appropriate expiry times
- Refresh tokens properly rotated
Common Tasks
Add New User Field
- Add migration:
ALTER TABLE users ADD COLUMN new_field TYPE; - Update
pkg/shared/types.goUser struct - Update affected API handlers
- Update database queries
Implement New Auth Method
- Create handler in
apps/management/api/auth.go - Add route in
apps/management/main.go - Update JWT claims if needed
- Add tests
- Document in API_CONTRACT.md
Add Statistics Tracking
- Design table schema in migration
- Create handler in
apps/management/api/stats.go - Implement aggregation queries
- Add indexes for performance
- Create views for common queries
Documentation Requirements
For every backend change, update:
- API_CONTRACT.md - API endpoint documentation
- BACKEND_README.md - Architecture and setup
- Code comments - Function documentation
- Migration files - Clear up/down migrations with comments
Deployment
Production Build
# Build binary
CGO_ENABLED=0 GOOS=linux GOARCH=amd64 go build \
-ldflags="-w -s" \
-o bin/vpnmanager \
./apps/management/main.go
# Run
./bin/vpnmanager
Systemd Service
[Unit]
Description=BarqNet Backend
After=network.target postgresql.service
[Service]
Type=simple
User=vpnmanager
WorkingDirectory=/opt/barqnet
Environment="JWT_SECRET=xxx"
Environment="DB_HOST=localhost"
ExecStart=/opt/barqnet/bin/vpnmanager
Restart=always
[Install]
WantedBy=multi-user.target
When to Use This Skill
✅ Use this skill when:
- Adding or modifying backend API endpoints
- Writing database migrations
- Implementing authentication/authorization
- Working with JWT tokens
- Integrating OpenVPN functionality
- Optimizing database queries
- Debugging backend issues
- Writing backend tests
❌ Don't use this skill for:
- Frontend/client development (use barqnet-client skill)
- Client-backend integration (use barqnet-integration skill)
- Documentation writing (use barqnet-documentation skill)
- Code auditing (use barqnet-audit skill)
Quick Reference
Build: go build -o bin/vpnmanager ./apps/management/main.go
Run: go run apps/management/main.go
Test: go test ./...
Format: go fmt ./...
Lint: golangci-lint run
Migrations: Auto-run on startup
Logs: Check console output with [TAG] prefixes
Success Criteria
A backend change is complete when:
- ✅ Code compiles without errors
- ✅ All tests pass
- ✅ Database migrations run successfully
- ✅ API endpoints return correct responses
- ✅ Error handling covers edge cases
- ✅ Security best practices followed
- ✅ Documentation updated
- ✅ Logging added for debugging