feat: first

This commit is contained in:
2025-08-13 19:36:09 +02:00
parent fd2ba2e999
commit 5fc4d1d997
17 changed files with 2622 additions and 111 deletions

289
README.md
View File

@@ -1,68 +1,267 @@
# Go gRPC Gateway Template
A simplified Go project template for gRPC services with HTTP/JSON gateway support, based on the [Go Standard Project Layout](https://github.com/golang-standards/project-layout).
A production-ready Go template for gRPC services with HTTP/JSON gateway support, featuring modern tooling, Docker support, and CI/CD integration.
## Project Structure
## 🚀 Features
- **Dual Protocol Support** - Serve both gRPC and REST APIs simultaneously
- **Modern Toolchain** - Uses [buf](https://buf.build) for Protocol Buffers management
- **Docker Ready** - Complete containerization with multi-stage builds
- **Testing** - Unit and integration tests with coverage
- **CI/CD** - GitHub Actions workflows for testing and deployment
- **Health Checks** - Built-in health monitoring endpoints
- **OpenAPI** - Auto-generated Swagger documentation
- **Configuration** - Environment-based config management
- **Observability** - Structured logging and metrics ready
## 📁 Project Structure
```
├── cmd/server/ # Main application entry point
├── cmd/server/ # Main application entry point
├── proto/helloworld/ # Protocol buffer definitions
├── internal/
│ ├── handler/ # gRPC and gateway handlers
── service/ # Business logic
├── pkg/pb/ # Generated protobuf files (auto-generated)
├── api/v1/ # Protocol buffer definitions
── justfile # Task runner configuration
│ ├── config/ # Configuration management
── health/ # Health check handlers
│ └── server/ # Server setup and middleware
├── pkg/ # Shared packages (if needed)
── tests/ # Integration tests
├── docker/ # Docker configuration
├── .github/workflows/ # CI/CD pipelines
├── buf.yaml # Buf configuration
├── buf.gen.yaml # Code generation config
├── docker-compose.yml # Local development
└── justfile # Task runner
```
## Prerequisites
## 🛠 Prerequisites
- Go 1.21+
- Protocol Buffers compiler (`protoc`)
- [just](https://github.com/casey/just) task runner
- [nushell](https://www.nushell.sh/) (for justfile execution)
- **Go 1.23+**
- **Docker & Docker Compose** (for containerized development)
- **[just](https://github.com/casey/just)** task runner
- **[buf](https://buf.build)** (installed automatically via `just install-deps`)
## Getting Started
## 🚦 Quick Start
1. Install dependencies:
```bash
just deps
```
### 1. Install Dependencies
```bash
just install-deps
```
2. Generate protobuf files:
```bash
just proto
```
### 2. Start Development Environment
```bash
# Start with Docker (recommended)
just dev-docker
3. Build and run the server:
```bash
just dev
```
# Or start locally
just dev
```
## Available Commands
### 3. Test the API
```bash
# gRPC endpoint
grpcurl -plaintext -d '{"name": "World"}' localhost:8080 helloworld.Greeter/SayHello
# HTTP endpoint
curl -X POST http://localhost:8090/v1/example/echo -d '{"name": "World"}' -H "Content-Type: application/json"
```
## 📋 Available Commands
### Development
- `just install-deps` - Install required tools (buf, protoc plugins)
- `just dev` - Start development server locally
- `just dev-docker` - Start with Docker Compose
- `just proto` - Generate protobuf files
- `just build` - Build the server binary
- `just run` - Run the server
- `just dev` - Full development workflow (deps + proto + run)
- `just test` - Run tests
- `just lint` - Run linter
### Testing & Quality
- `just test` - Run unit tests
- `just test-integration` - Run integration tests
- `just test-coverage` - Run tests with coverage report
- `just lint` - Run linter and format check
- `just format` - Format code
### Docker & Deployment
- `just docker-build` - Build Docker image
- `just docker-run` - Run container locally
- `just docker-push` - Push to registry
### Utilities
- `just clean` - Clean build artifacts
- `just docs` - Generate and serve API documentation
- `just health` - Check service health
## API Endpoints
## 🌐 API Documentation
The server runs on two ports:
- gRPC server: `:8080`
- HTTP gateway: `:8081`
### Endpoints
### Example HTTP endpoints:
- `GET /v1/examples` - List all examples
- `POST /v1/examples` - Create a new example
- `GET /v1/examples/{id}` - Get a specific example
| Method | Path | Description |
|--------|------|-------------|
| `POST` | `/v1/example/echo` | Echo the input name |
| `GET` | `/health` | Health check endpoint |
| `GET` | `/metrics` | Prometheus metrics (if enabled) |
| `GET` | `/docs` | OpenAPI documentation |
## Monorepo Integration
### Example Requests
This template is designed to be integration-friendly for monorepo structures by:
- Excluding shared proto folders
- Using internal packages for service-specific logic
- Minimal external dependencies
- Clear separation of concerns
**Echo Request:**
```bash
curl -X POST http://localhost:8090/v1/example/echo \
-H "Content-Type: application/json" \
-d '{"name": "World"}'
```
**Response:**
```json
{
"message": "Hello World"
}
```
**Health Check:**
```bash
curl http://localhost:8090/health
```
**Response:**
```json
{
"status": "ok",
"timestamp": "2025-08-13T19:30:00Z",
"version": "1.0.0"
}
```
## 🐳 Docker Usage
### Development with Docker Compose
```bash
# Start all services
just dev-docker
# View logs
docker-compose logs -f
# Stop services
docker-compose down
```
### Production Docker Build
```bash
# Build optimized image
just docker-build
# Run container
just docker-run
```
## 🧪 Testing
```bash
# Run all tests
just test
# Run with coverage
just test-coverage
# Run integration tests
just test-integration
# Run specific test
go test -v ./internal/server -run TestServerHealth
```
## 🔧 Configuration
The service can be configured via environment variables:
| Variable | Default | Description |
|----------|---------|-------------|
| `SERVER_GRPC_PORT` | `8080` | gRPC server port |
| `SERVER_HTTP_PORT` | `8090` | HTTP gateway port |
| `LOG_LEVEL` | `info` | Logging level (debug, info, warn, error) |
| `LOG_FORMAT` | `json` | Log format (json, text) |
| `METRICS_ENABLED` | `true` | Enable Prometheus metrics |
Example `.env` file:
```bash
SERVER_GRPC_PORT=9090
SERVER_HTTP_PORT=8080
LOG_LEVEL=debug
LOG_FORMAT=text
```
## 🔄 Adding New Services
1. **Define the service in protobuf:**
```protobuf
service UserService {
rpc CreateUser(CreateUserRequest) returns (CreateUserResponse) {
option (google.api.http) = {
post: "/v1/users"
body: "*"
};
}
}
```
2. **Generate code:**
```bash
just proto
```
3. **Implement the service:**
```go
type UserService struct {
helloworldpb.UnimplementedUserServiceServer
}
func (s *UserService) CreateUser(ctx context.Context, req *helloworldpb.CreateUserRequest) (*helloworldpb.CreateUserResponse, error) {
// Implementation here
return &helloworldpb.CreateUserResponse{}, nil
}
```
4. **Register in server:**
```go
helloworldpb.RegisterUserServiceServer(s, &UserService{})
helloworldpb.RegisterUserServiceHandler(ctx, gwmux, conn)
```
## 🚀 Deployment
### GitHub Actions
The template includes automated workflows:
- **CI**: Runs tests, linting, and security scans on PRs
- **CD**: Builds and pushes Docker images on releases
- **Dependency Updates**: Automated dependency updates
### Manual Deployment
```bash
# Build for production
just build
# Create Docker image
just docker-build
# Deploy to your platform
just docker-push
```
## 🤝 Contributing
1. Fork the repository
2. Create a feature branch
3. Make your changes
4. Run tests: `just test`
5. Submit a pull request
## 🔗 Useful Links
- [gRPC-Gateway Documentation](https://grpc-ecosystem.github.io/grpc-gateway/)
- [Protocol Buffers Guide](https://developers.google.com/protocol-buffers)
- [Buf Documentation](https://buf.build/docs/)
- [Go Standard Project Layout](https://github.com/golang-standards/project-layout)