/
s4ze
/
api-lab3
Обзор
Документация
Войти
/
s4ze
/
api-lab3
Код
Запросы
0
Задачи
Вики
Пакеты
0
Релизы
0
CI/CD
Аналитика
Безопасность
master
client/examples.go
163 строки
4 KB
s4ze
Добавлен бэкенд и клиент (готовые)
30 дек 2025, 08:31
30 дек 2025, 08:31
f648d9c
Код
Авторство
О чём код?
package main import ( "fmt" "log" "os" ) // ExampleBasicUsage demonstrates basic client usage func ExampleBasicUsage() { baseURL := os.Getenv("API_BASE_URL") if baseURL == "" { baseURL = "http://localhost:8000" } client := NewClient(baseURL) // Example: Login and fetch categories fmt.Println("=== Basic Usage Example ===") // Step 1: Authentication fmt.Println("Step 1: Authenticating...") err := client.Login("user@example.com", "password") if err != nil { log.Printf("Authentication failed: %v", err) return } fmt.Println("✓ Authentication successful") // Step 2: Fetch data fmt.Println("\nStep 2: Fetching categories...") categories, pagination, err := client.GetCategories(5, 0) if err != nil { log.Printf("Failed to fetch categories: %v", err) return } fmt.Printf("✓ Found %d categories (total: %d)\n", len(categories), pagination.TotalCount) // Step 3: Create new category fmt.Println("\nStep 3: Creating new category...") result, err := client.CreateCategory("New Category", "new-category", nil) if err != nil { log.Printf("Failed to create category: %v", err) return } fmt.Printf("✓ Category created: %+v\n", result) } // ExampleErrorHandling demonstrates error handling func ExampleErrorHandling() { client := NewClient("http://localhost:8000") fmt.Println("\n=== Error Handling Example ===") // Try to access protected resource without authentication fmt.Println("Attempting to access protected resource without auth...") _, err := client.CreateCategory("Test", "test", nil) if err != nil { fmt.Printf("Expected error: %v\n", err) } // Handle various error types if err != nil { errMsg := err.Error() if err.Error() == "not authenticated" { fmt.Println("Action required: Please authenticate first") } else { fmt.Printf("API Error: %s\n", errMsg) } } } // ExamplePagination demonstrates pagination handling func ExamplePagination() { client := NewClient("http://localhost:8000") fmt.Println("\n=== Pagination Example ===") // Fetch items with pagination limit := 10 offset := 0 for offset < 50 { fmt.Printf("\nFetching items %d to %d...\n", offset, offset+limit) items, pagination, err := client.GetProducts(limit, offset, "", nil, nil) if err != nil { log.Printf("Error: %v", err) break } fmt.Printf("Retrieved %d items (total: %d)\n", len(items), pagination.TotalCount) if pagination.Link == "" { fmt.Println("No more items") break } offset += limit } } // ExampleIdempotency demonstrates idempotent operations func ExampleIdempotency() { client := NewClient("http://localhost:8000") client.SetAccessToken("test_token") fmt.Println("\n=== Idempotent Operation Example ===") productData := map[string]interface{}{ "description": "Unique Product", "brand_id": 1, "category_id": 1, } // First request fmt.Println("First request: Creating product...") result1, err := client.CreateProduct("Test Product", "test-product-unique", productData) if err != nil { fmt.Printf("Error: %v\n", err) } else { fmt.Printf("Created: %+v\n", result1) } // Duplicate request with same idempotency key fmt.Println("\nSecond request (same slug, should be idempotent)...") result2, err := client.CreateProduct("Test Product", "test-product-unique", productData) if err != nil { fmt.Printf("Error: %v\n", err) } else { fmt.Printf("Result: %+v\n", result2) fmt.Println("Note: Should return same product without creating duplicate") } } // ExampleTokenRefresh demonstrates token refresh mechanism func ExampleTokenRefresh() { client := NewClient("http://localhost:8000") fmt.Println("\n=== Token Refresh Example ===") // Set initial tokens (normally from login) client.SetAccessToken("initial_token") client.refreshToken = "refresh_token_value" fmt.Println("Current access token set") // Check and refresh if needed fmt.Println("Checking token validity...") if err := client.EnsureValidToken(); err != nil { fmt.Printf("Token error: %v\n", err) } else { fmt.Println("Token is valid") } // Manually refresh fmt.Println("\nManually refreshing token...") if err := client.RefreshAccessToken(); err != nil { fmt.Printf("Refresh failed: %v\n", err) } else { fmt.Println("Token refreshed successfully") } }