-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathdemo.go
More file actions
382 lines (319 loc) · 10.2 KB
/
Copy pathdemo.go
File metadata and controls
382 lines (319 loc) · 10.2 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
package main
import (
"fmt"
"math/rand"
"strings"
"sync"
"time"
"advanced-go-project/pkg/models"
"advanced-go-project/pkg/services"
"advanced-go-project/pkg/utils"
)
// DemoRunner demonstrates various advanced Go features
type DemoRunner struct {
services *demoServices
}
type demoServices struct {
rateLimiter *services.RateLimiter
workerPool *services.WorkerPool
cache *services.CacheService
metrics *services.MetricsService
}
// NewDemoRunner creates a new demo runner
func NewDemoRunner() *DemoRunner {
return &DemoRunner{
services: &demoServices{
rateLimiter: services.NewRateLimiter(5, time.Minute),
workerPool: services.NewWorkerPool(3),
cache: services.NewCacheService(),
metrics: services.NewMetricsService(),
},
}
}
// RunAllDemos runs all demonstration functions
func (dr *DemoRunner) RunAllDemos() {
fmt.Println("🎯 Advanced Go Project - Feature Demonstrations")
fmt.Println(strings.Repeat("=", 49))
fmt.Println()
dr.demonstrateUtilityFunctions()
dr.demonstrateServicePatterns()
dr.demonstrateAdvancedStructures()
dr.demonstrateAsyncPatterns()
dr.demonstrateValidationSystem()
dr.demonstrateMetricsCollection()
fmt.Println("\n✅ All demonstrations completed successfully!")
}
// demonstrateUtilityFunctions shows utility function usage
func (dr *DemoRunner) demonstrateUtilityFunctions() {
fmt.Println("📧 Utility Functions Demo")
fmt.Println(strings.Repeat("-", 25))
// Email validation
email := "user@example.com"
isValid := utils.IsValidEmail(email)
fmt.Printf("Email validation: %t\n", isValid)
// UUID validation
uuid := "550e8400-e29b-41d4-a716-446655440000"
isValidUUID := utils.IsValidUUID(uuid)
fmt.Printf("UUID validation: %t\n", isValidUUID)
// Password validation
password := "StrongPassword123!"
validationErrors := utils.ValidatePassword(password)
fmt.Printf("Password validation: %t (errors: %d)\n", len(validationErrors) == 0, len(validationErrors))
// String operations
snakeCase := utils.ToSnakeCase("CamelCaseString")
camelCase := utils.ToCamelCase("snake_case_string")
fmt.Printf("Snake case: %s, Camel case: %s\n", snakeCase, camelCase)
// Cryptographic operations
token := utils.GenerateSecureToken(16)
hash := utils.SHA256Hash("test string")
fmt.Printf("Generated token: %s\n", token)
fmt.Printf("SHA256 hash: %s...\n", hash[:16])
// Time operations
isWeekend := utils.IsWeekend(time.Now())
isBusinessHours := utils.IsBusinessHours(time.Now())
duration := utils.FormatDuration(2*time.Hour + 30*time.Minute)
fmt.Printf("Is weekend: %t\n", isWeekend)
fmt.Printf("Is business hours: %t\n", isBusinessHours)
fmt.Printf("Duration format: %s\n", duration)
fmt.Println()
}
// demonstrateServicePatterns shows service layer patterns
func (dr *DemoRunner) demonstrateServicePatterns() {
fmt.Println("🔧 Service Patterns Demo")
fmt.Println(strings.Repeat("-", 25))
// Rate limiting demonstration
fmt.Print("Rate limiting test: ")
for i := 1; i <= 7; i++ {
allowed := dr.services.rateLimiter.Allow()
fmt.Printf("Request %d allowed: %t\n", i, allowed)
}
// Worker pool demonstration
dr.services.workerPool.Start()
var wg sync.WaitGroup
for i := 1; i <= 5; i++ {
wg.Add(1)
task := services.Task{
ID: fmt.Sprintf("task-%d", i),
Data: fmt.Sprintf("Task %d data", i),
Fn: func(data interface{}) error {
fmt.Printf(" Worker processing %s\n", data)
time.Sleep(100 * time.Millisecond)
wg.Done()
return nil
},
}
dr.services.workerPool.Submit(task)
}
wg.Wait()
fmt.Println("Worker pool tasks completed")
dr.services.workerPool.Stop()
// Cache demonstration
dr.services.cache.Set("test-key", "test-value", time.Minute)
if value, found := dr.services.cache.Get("test-key"); found {
_ = value // Use the value
}
// Metrics demonstration
dr.services.metrics.Start()
dr.services.metrics.SetActiveUsers(3)
dr.services.metrics.IncrementRequest("/api/users")
dr.services.metrics.IncrementRequest("/api/products")
dr.services.metrics.IncrementRequest("/api/orders")
metrics := dr.services.metrics.GetMetrics()
if activeUsers, ok := metrics["active_users"]; ok {
fmt.Printf("Collected metrics: %v\n", activeUsers)
}
dr.services.metrics.Stop()
fmt.Println()
}
// demonstrateAdvancedStructures shows advanced data structures
func (dr *DemoRunner) demonstrateAdvancedStructures() {
fmt.Println("🏗️ Advanced Data Structures Demo")
fmt.Println(strings.Repeat("-", 32))
// User model demonstration
user := &models.User{
ID: 1,
Username: "demo_user",
Email: "demo@example.com",
FirstName: "John",
LastName: "Doe",
IsActive: true,
Metadata: map[string]interface{}{
"preferences": map[string]interface{}{
"theme": "dark",
"lang": "en",
},
"created_by": "system",
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
fmt.Printf("User: %s (%s)\n", user.Username, user.Email)
fmt.Printf("Full name: %s\n", user.GetFullName())
metadataKeys := user.GetMetadataKeys()
fmt.Printf("Metadata keys: %v\n", metadataKeys)
// Product model demonstration
product := &models.Product{
ID: 1,
Name: "Advanced Go Book",
Description: "A comprehensive guide to advanced Go programming",
Price: 49.99,
Category: "Books",
StockQuantity: 100,
IsActive: true,
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
fmt.Printf("Product: %s - $%.2f\n", product.Name, product.Price)
fmt.Printf("In stock: %t (quantity: %d)\n", product.IsInStock(), product.StockQuantity)
fmt.Printf("Can purchase 5 items: %t\n", product.CanPurchase(5))
// Order model demonstration
order := &models.Order{
ID: 1,
UserID: user.ID,
Status: "pending",
TotalAmount: 149.97,
Items: []*models.OrderItem{
{
ID: 1,
OrderID: 1,
ProductID: product.ID,
Quantity: 3,
UnitPrice: product.Price,
},
},
CreatedAt: time.Now(),
UpdatedAt: time.Now(),
}
fmt.Printf("Order status: %s\n", order.Status)
fmt.Printf("Can transition to confirmed: %t\n", order.CanTransitionTo("confirmed"))
fmt.Printf("Can transition to delivered: %t\n", order.CanTransitionTo("delivered"))
fmt.Println()
}
// demonstrateAsyncPatterns shows asynchronous programming patterns
func (dr *DemoRunner) demonstrateAsyncPatterns() {
fmt.Println("⚡ Async Patterns Demo")
fmt.Println(strings.Repeat("-", 20))
// Channel-based communication
resultCh := make(chan string, 3)
errorCh := make(chan error, 3)
// Start multiple goroutines
for i := 0; i < 3; i++ {
go func(id int) {
if id == 2 {
errorCh <- fmt.Errorf("simulated error for task %d", id)
return
}
time.Sleep(time.Duration(rand.Intn(100)) * time.Millisecond)
resultCh <- fmt.Sprintf("Result from task %d", id)
}(i)
}
// Collect results
for i := 0; i < 3; i++ {
select {
case result := <-resultCh:
fmt.Printf(" Received: %s\n", result)
case err := <-errorCh:
fmt.Printf(" Error: %s\n", err)
case <-time.After(time.Second):
fmt.Println(" Timeout waiting for result")
}
}
// Retry pattern demonstration
fmt.Println("Retry pattern demo:")
err := retryWithBackoff(func() error {
// Simulate a function that fails the first time
if rand.Float64() < 0.5 {
return fmt.Errorf("random failure")
}
return nil
}, 3, time.Millisecond*50)
if err != nil {
fmt.Printf(" Failed after retries: %v\n", err)
} else {
fmt.Println(" Succeeded after retries")
}
fmt.Println()
}
// demonstrateValidationSystem shows validation patterns
func (dr *DemoRunner) demonstrateValidationSystem() {
fmt.Println("✅ Validation System Demo")
fmt.Println(strings.Repeat("-", 27))
passwords := []string{
"weak",
"StrongPassword123!",
"NoSpecialChars123",
"nouppercase123!",
}
for _, password := range passwords {
errors := utils.ValidatePassword(password)
displayPassword := password
if len(password) > 10 {
displayPassword = password[:8] + "..."
}
fmt.Printf(" Password '%s': valid=%t, errors=%d\n",
displayPassword, len(errors) == 0, len(errors))
}
fmt.Println()
}
// demonstrateMetricsCollection shows metrics and monitoring
func (dr *DemoRunner) demonstrateMetricsCollection() {
fmt.Println("📊 Metrics Collection Demo")
fmt.Println(strings.Repeat("-", 27))
metrics := dr.services.metrics
metrics.Start()
// Simulate some activity
endpoints := []string{"/api/users", "/api/products", "/api/orders"}
for i := 0; i < 10; i++ {
endpoint := endpoints[i%len(endpoints)]
metrics.IncrementRequest(endpoint)
// Simulate some errors
if i%3 == 0 {
metrics.IncrementError(endpoint)
}
}
metrics.SetActiveUsers(3)
// Get and display metrics
metricsData := metrics.GetMetrics()
if activeUsers, ok := metricsData["active_users"]; ok {
fmt.Printf("Active users: %v\n", activeUsers)
}
if requests, ok := metricsData["requests"].(map[string]int64); ok {
fmt.Println("Request counts:")
for endpoint, count := range requests {
fmt.Printf(" %s: %d requests\n", endpoint, count)
}
}
if errors, ok := metricsData["errors"].(map[string]int64); ok {
fmt.Println("Error counts:")
for endpoint, count := range errors {
fmt.Printf(" %s: %d errors\n", endpoint, count)
}
}
metrics.Stop()
fmt.Println()
}
// retryWithBackoff implements exponential backoff retry pattern
func retryWithBackoff(fn func() error, maxRetries int, baseDelay time.Duration) error {
var err error
for i := 0; i < maxRetries; i++ {
fmt.Printf(" Attempt %d\n", i+1)
if err = fn(); err == nil {
fmt.Printf(" Succeeded after %d attempts\n", i+1)
return nil
}
if i < maxRetries-1 {
delay := baseDelay * time.Duration(1<<uint(i)) // Exponential backoff
time.Sleep(delay)
}
}
return fmt.Errorf("failed after %d attempts: %w", maxRetries, err)
}
// runAdvancedDemo is the main entry point for demo mode
func runAdvancedDemo() {
demo := NewDemoRunner()
demo.RunAllDemos()
}
// runDemo is an alias for runAdvancedDemo
func runDemo() {
runAdvancedDemo()
}