Go-based REST API with Gin framework, PostgreSQL database, and blockchain integration for the DanaVerse crowdfunding platform.
# DanaVerse API - Cursor Rules
## 🚀 API Overview
Go-based REST API with Gin framework, PostgreSQL database, and blockchain integration for the DanaVerse crowdfunding platform.
## 🎯 Technology Stack
- **Language**: Go 1.22+
- **Framework**: Gin web framework
- **Database**: PostgreSQL with migrations
- **Authentication**: JWT-based auth
- **Blockchain**: Ethereum integration
- **Testing**: Go testing package
## 📁 Project Structure
```
apps/api/
├── cmd/ # Application entry points
├── internal/ # Private application code
│ ├── handlers/ # HTTP handlers
│ ├── middleware/ # HTTP middleware
│ ├── models/ # Data models
│ ├── services/ # Business logic
│ └── repository/ # Data access layer
├── pkg/ # Public library code
├── migrations/ # Database migrations
├── docs/ # Documentation
└── tests/ # Test files
```
## 🎯 Go Standards
### Code Structure
```go
// Use proper Go package structure
package handlers
import (
"net/http"
"github.com/gin-gonic/gin"
)
// Handler function with proper error handling
func GetProjects(c *gin.Context) {
projects, err := projectService.GetAll()
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to fetch projects",
})
return
}
c.JSON(http.StatusOK, gin.H{
"data": projects,
})
}
```
### Go Guidelines
- Use proper package structure
- Follow Go naming conventions
- Use proper error handling
- Implement proper logging
- Use context for cancellation
- Follow Go best practices
## 🎯 API Design Standards
### RESTful API Design
```go
// Use proper HTTP methods and status codes
func CreateProject(c *gin.Context) {
var project models.Project
if err := c.ShouldBindJSON(&project); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Invalid request body",
})
return
}
// Business logic here
createdProject, err := projectService.Create(project)
if err != nil {
c.JSON(http.StatusInternalServerError, gin.H{
"error": "Failed to create project",
})
return
}
c.JSON(http.StatusCreated, gin.H{
"data": createdProject,
})
}
```
### API Guidelines
- Use proper HTTP status codes
- Implement proper request validation
- Use consistent response format
- Implement proper error handling
- Use proper authentication
- Follow RESTful principles
## 🗄️ Database Standards
### Model Definition
```go
// models/project.go
type Project struct {
ID uint `json:"id" gorm:"primaryKey"`
Title string `json:"title" gorm:"not null"`
Description string `json:"description"`
Goal float64 `json:"goal" gorm:"not null"`
Raised float64 `json:"raised" gorm:"default:0"`
Status string `json:"status" gorm:"default:'active'"`
CreatedAt time.Time `json:"created_at"`
UpdatedAt time.Time `json:"updated_at"`
}
```
### Database Guidelines
- Use proper GORM models
- Implement proper migrations
- Use proper indexing
- Implement proper constraints
- Use transactions for complex operations
- Follow database best practices
## 🔐 Authentication & Authorization
### JWT Implementation
```go
// middleware/auth.go
func AuthMiddleware() gin.HandlerFunc {
return func(c *gin.Context) {
token := c.GetHeader("Authorization")
if token == "" {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Authorization header required",
})
c.Abort()
return
}
// Validate token
claims, err := validateToken(token)
if err != nil {
c.JSON(http.StatusUnauthorized, gin.H{
"error": "Invalid token",
})
c.Abort()
return
}
c.Set("user_id", claims.UserID)
c.Next()
}
}
```
### Security Guidelines
- Use proper JWT implementation
- Implement proper password hashing
- Use proper rate limiting
- Implement proper CORS
- Use proper input validation
- Follow security best practices
## 🔗 Blockchain Integration
### Ethereum Integration
```go
// services/blockchain.go
type BlockchainService struct {
client *ethclient.Client
}
func (s *BlockchainService) GetBalance(address string) (*big.Int, error) {
account := common.HexToAddress(address)
balance, err := s.client.BalanceAt(context.Background(), account, nil)
if err != nil {
return nil, err
}
return balance, nil
}
```
### Blockchain Guidelines
- Use proper error handling for blockchain calls
- Implement proper gas estimation
- Use proper transaction confirmation
- Implement proper event listening
- Use proper contract interaction
- Follow blockchain best practices
## 🧪 Testing Standards
### Unit Testing
```go
// tests/handlers/project_test.go
func TestGetProjects(t *testing.T) {
// Setup
gin.SetMode(gin.TestMode)
router := gin.New()
router.GET("/projects", GetProjects)
// Test
req, _ := http.NewRequest("GET", "/projects", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, req)
// Assertions
assert.Equal(t, http.StatusOK, w.Code)
assert.Contains(t, w.Body.String(), "data")
}
```
### Testing Guidelines
- Write unit tests for all handlers
- Test business logic thoroughly
- Mock external dependencies
- Use proper test data
- Aim for 80%+ coverage
- Test error scenarios
## 🚀 Performance Optimization
### Performance Best Practices
```go
// Use proper database queries
func (r *ProjectRepository) GetProjectsWithPagination(limit, offset int) ([]models.Project, error) {
var projects []models.Project
err := r.db.Limit(limit).Offset(offset).Find(&projects).Error
return projects, err
}
// Use proper caching
func (s *ProjectService) GetProject(id uint) (*models.Project, error) {
// Check cache first
if cached, found := s.cache.Get(fmt.Sprintf("project:%d", id)); found {
return cached.(*models.Project), nil
}
// Fetch from database
project, err := s.repository.GetByID(id)
if err != nil {
return nil, err
}
// Cache the result
s.cache.Set(fmt.Sprintf("project:%d", id), project, time.Hour)
return project, nil
}
```
### Performance Guidelines
- Use proper database indexing
- Implement proper caching
- Use proper connection pooling
- Optimize database queries
- Use proper pagination
- Monitor performance metrics
## 📊 Logging & Monitoring
### Structured Logging
```go
// Use structured logging
import "github.com/sirupsen/logrus"
func (h *ProjectHandler) CreateProject(c *gin.Context) {
log := logrus.WithFields(logrus.Fields{
"handler": "CreateProject",
"user_id": c.GetString("user_id"),
})
log.Info("Creating new project")
// Handler logic here
log.Info("Project created successfully")
}
```
### Monitoring Guidelines
- Use structured logging
- Implement proper error tracking
- Use proper metrics collection
- Implement proper health checks
- Use proper performance monitoring
- Follow observability best practices
## 🔒 Security Best Practices
### Input Validation
```go
// Use proper input validation
type CreateProjectRequest struct {
Title string `json:"title" binding:"required,min=3,max=100"`
Description string `json:"description" binding:"required,min=10,max=1000"`
Goal float64 `json:"goal" binding:"required,min=0.01"`
}
func CreateProject(c *gin.Context) {
var req CreateProjectRequest
if err := c.ShouldBindJSON(&req); err != nil {
c.JSON(http.StatusBadRequest, gin.H{
"error": "Validation failed",
"details": err.Error(),
})
return
}
// Process request
}
```
### Security Guidelines
- Validate all inputs
- Use proper SQL injection prevention
- Implement proper rate limiting
- Use proper CORS configuration
- Implement proper authentication
- Follow OWASP guidelines
## 🚨 Common Pitfalls to Avoid
### Don't
- Don't ignore errors
- Don't use global variables
- Don't forget to close resources
- Don't ignore context cancellation
- Don't skip input validation
### Do
- Do handle errors properly
- Do use proper logging
- Do implement proper testing
- Do use proper error responses
- Do follow Go best practices
## 📚 Documentation
### API Documentation
```go
// @Summary Create a new project
// @Description Create a new crowdfunding project
// @Tags projects
// @Accept json
// @Produce json
// @Param project body CreateProjectRequest true "Project data"
// @Success 201 {object} ProjectResponse
// @Failure 400 {object} ErrorResponse
// @Failure 500 {object} ErrorResponse
// @Router /projects [post]
func CreateProject(c *gin.Context) {
// Handler implementation
}
```
### Documentation Standards
- Use Swagger/OpenAPI annotations
- Document all endpoints
- Include request/response examples
- Document error codes
- Keep documentation up-to-date
## 🔧 Development Commands
```bash
# Development
go run cmd/main.go # Run the application
go build cmd/main.go # Build the application
# Testing
go test ./... # Run all tests
go test -v ./... # Run tests with verbose output
go test -cover ./... # Run tests with coverage
# Linting
golangci-lint run # Run linter
go fmt ./... # Format code
go vet ./... # Run go vet
# Database
go run cmd/migrate.go up # Run migrations
go run cmd/migrate.go down # Rollback migrations
```
## 🎯 Code Review Checklist
### Before Submitting PR
- [ ] Go code follows best practices
- [ ] All tests pass
- [ ] No linting errors
- [ ] Proper error handling
- [ ] Performance optimization
- [ ] Security considerations
- [ ] Documentation updated
- [ ] Database migrations included
---
**Remember**: Write Go code that's fast, safe, and maintainable! 🚀
Workflows from the Neura Market marketplace related to this Cursor resource