All authors

Claude Skills by HoangNguyen0403
github.com/HoangNguyen04031,434 skills30 installs1,975 views
- Golang ConcurrencyDon’t fire off bare goroutines in the loop. Give each one a defined lifetime and a shutdown path. The usual pattern is: - pass a `context.Context` into the work - capture the loop variable correctly - use `errgroup` or a `sync.WaitGroup` to track completion - use `select` on `ctx.Done()` inside long-running or blocking work - close channels from the producer side only, so consumers can exit cleanly Example with `errgroup`: ```go func processOrders(ctx context.Context, orders []Order) error { ...Votes: 0GitHub stars: 549
- Golang ConcurrencyPrefer not to have multiple goroutines mutate the counter directly. The idiomatic Go approach is to send increment events over a channel to a single owner goroutine that updates the counter, which avoids races. If shared mutation is unavoidable, protect the counter with `sync.Mutex` or use `sync/atomic` for simple numeric increments.Votes: 0GitHub stars: 549
- Golang ConcurrencyUse: ```bash go test -race ./... ``` For a specific package: ```bash go test -race ./path/to/package ``` For a single test: ```bash go test -race ./path/to/package -run TestName ``` The `-race` flag enables Go’s race detector to catch data races during the test run.Votes: 0GitHub stars: 549
- Golang ConfigurationFor production, load database credentials from environment variables or a secret manager that exposes them as env vars at runtime. In Go, put them into a typed `Config` struct at startup, validate required fields immediately, and fail fast if anything is missing. Avoid hardcoding secrets, committing `.env` files with real credentials, or reading config from globals throughout the app. Typical fields would be things like `DB_HOST`, `DB_PORT`, `DB_USER`, `DB_PASSWORD`, and `DB_NAME`. You can lo...Votes: 0GitHub stars: 549
- Golang ConfigurationUsually no. A global `config AppConfig` is an anti-pattern in Go apps because it creates hidden dependencies, makes testing harder, and couples runtime state across the whole process. Better approach: - load config once at startup - unmarshal into a typed `Config` struct - validate required fields immediately - pass that config into constructors/services that need it Example: ```go type Config struct { Port string DBURL string LogLevel string } func NewServer(cfg Config) *Server { retu...Votes: 0GitHub stars: 549
- Golang ConfigurationValidate required config at startup and fail fast if `DATABASE_URL` is missing. In Go, load config into a typed `Config` struct, read env vars before starting the app, and return an error immediately if a required value is empty. Then inject that config into your services instead of letting code read globals later. Example: ```go package config import ( "fmt" "os" ) type Config struct { DatabaseURL string Port string } func Load() (Config, error) { cfg := Config{ DatabaseURL: os.Getenv...Votes: 0GitHub stars: 549
- Golang Database`var db *sql.DB` at package level creates hidden global state, which makes testing, lifecycle management, and transaction boundaries harder. Main problems: - It hides dependencies instead of injecting them. - It encourages context-less calls from anywhere. - It makes pool configuration and startup/shutdown ownership unclear. - It couples unrelated code to one shared connection handle. - It makes mocking or swapping the data layer awkward in tests. Important nuance: `*sql.DB` is concurrency-sa...Votes: 0GitHub stars: 549
- Golang DatabaseUse `QueryContext` plus `defer rows.Close()` immediately after checking the query error, then always check `rows.Err()` after the loop. ```go func ListUsers(ctx context.Context, db *sql.DB) ([]User, error) { rows, err := db.QueryContext(ctx, ` SELECT id, email FROM users ORDER BY id `) if err != nil { return nil, err } defer rows.Close() var users []User for rows.Next() { var u User if err := rows.Scan(&u.ID, &u.Email); err != nil { return nil, err } users = append(users, u) } if err := rows....Votes: 0GitHub stars: 549
- Golang DatabaseUse `db.QueryContext()` in a Go repository. Why: - It accepts `context.Context`, so request deadlines, cancellation, and tracing propagate into the DB call. - It prevents queries from ignoring timeout/cancel signals. - It matches good repository design where every query path is context-aware. Typical pattern: ```go rows, err := db.QueryContext(ctx, query, args...) if err != nil { return nil, err } defer rows.Close() ``` Also check `rows.Err()` after iteration. Use plain `db.Query()` only if y...Votes: 0GitHub stars: 549
- Golang Error HandlingUse `fmt.Errorf` with `%w`: ```go if err != nil { return fmt.Errorf("failed to load config: %w", err) } ``` That adds context while preserving the original error in the chain, so callers can still do: ```go if errors.Is(err, os.ErrNotExist) { // handle missing file } var pathErr *os.PathError if errors.As(err, &pathErr) { // handle typed error } ``` Use `%w` when wrapping. If you use `%v` or `%s`, callers cannot reliably check the original error with `errors.Is` or `errors.As`.Votes: 0GitHub stars: 549
- Golang Error HandlingDefine an exported sentinel with `errors.New`, then wrap lower-level errors with context and check via `errors.Is`. ```go package repository import ( "errors" "fmt" ) var ErrNotFound = errors.New("not found") func (r *Repo) Get(id string) (*Item, error) { item, err := r.load(id) if err != nil { if errors.Is(err, ErrNotFound) { return nil, fmt.Errorf("get item %q: %w", id, err) } return nil, fmt.Errorf("get item %q: %w", id, err) } return item, nil } ``` If your repository maps another source ...Votes: 0GitHub stars: 549
- Golang Error HandlingUsually no. Ignoring an `error` with `_` is a Go anti-pattern because it silently swallows failure. In most cases you should either handle it or return it with context, for example: ```go if err := doThing(); err != nil { return fmt.Errorf("do thing: %w", err) } ``` The rare cases where it can be acceptable are when you are intentionally discarding a result that is guaranteed or explicitly documented to be safe to ignore, and even then it is often better to make that intent obvious in code. F...Votes: 0GitHub stars: 549
- Golang LanguageThe idiomatic way is a `const` block, often with a custom type and `iota` for enum-like values. ```go type Status int const ( StatusPending Status = iota StatusRunning StatusDone ) ``` Use plain `const` values for unrelated constants, and `iota` when the constants are a related sequence.Votes: 0GitHub stars: 549
- Golang LanguageIn Go, keep imports in a single `import` block, grouped and automatically formatted with `gofmt` or `goimports`. General structure: ```go import ( "context" "fmt" "github.com/acme/project/internal/service" ) ``` Use these rules: - Standard library imports first - Blank line - Third-party or local project imports after that - Let `goimports` sort and clean them automatically - Avoid unused imports - Prefer one grouped `import (...)` block when there are multiple imports Also: - Use short, lowe...Votes: 0GitHub stars: 549
- Golang LanguageAvoid these common Go anti-patterns: - Using `init()` for app setup instead of explicit constructors like `NewService()` - Relying on global mutable state instead of dependency injection - Calling `panic` for normal error handling instead of returning `error` - Ignoring errors with `_` or delaying error handling - Creating large, broad interfaces instead of small consumer-side interfaces - Using non-idiomatic naming, like underscores in package names or stuttering names such as `log.LogError`...Votes: 0GitHub stars: 549
- Golang LoggingUse Go's `log/slog` for structured logging. Set it up once in `main()` with a JSON handler, then inject a logger into your HTTP server and middleware. For each request, attach contextual fields like `request_id`, `trace_id`, `method`, `path`, and `status` so logs are machine-readable and easy to filter. Prefer leveled logs: - `Debug` for detailed diagnostics - `Info` for normal request lifecycle events - `Warn` for unusual but recoverable conditions - `Error` for failures Example pattern: ```...Votes: 0GitHub stars: 549
- Golang LoggingPass it explicitly, not as a global. The usual Go pattern is: 1. Create the base logger in `main()` 2. Inject it into top-level dependencies via constructors 3. Derive child loggers per layer with `With(...)` 4. Add request-scoped values like request ID / trace ID at the edge Example with `log/slog`: ```go package main import ( "context" "log/slog" "os" ) type UserRepo struct { logger *slog.Logger } func NewUserRepo(logger *slog.Logger) *UserRepo { return &UserRepo{logger: logger} } func (r *...Votes: 0GitHub stars: 549
- Golang LoggingUse `Warn` for expected-but-notable errors like `user not found` when they can happen in normal flow and are worth observing. Use `Error` for unexpected failures you need to investigate. Panics are not normal control flow, so log them at `Error` or higher with full context, then recover or crash at the boundary that owns the process. As a rule of thumb: - `Info`: normal events - `Warn`: expected anomalies or client/domain issues - `Error`: unexpected failures, broken dependencies, recoverable...Votes: 0GitHub stars: 549
- Golang SecurityUse parameterized queries with placeholders and pass user input as separate arguments to `Query`, `QueryRow`, or `Exec`. Do not build SQL with string concatenation or `fmt.Sprintf`. ```go package main import ( "database/sql" "fmt" _ "github.com/lib/pq" ) type User struct { ID int Email string } func getUserByEmail(db *sql.DB, email string) (*User, error) { const q = `SELECT id, email FROM users WHERE email = $1` var u User if err := db.QueryRow(q, email).Scan(&u.ID, &u.Email); err != nil {...Votes: 0GitHub stars: 549
- Golang SecurityUse `crypto/rand`, not `math/rand`, for a password-reset token. ```go package main import ( "crypto/rand" "encoding/base64" "fmt" ) func generateResetToken(n int) (string, error) { b := make([]byte, n) if _, err := rand.Read(b); err != nil { return "", err } return base64.RawURLEncoding.EncodeToString(b), nil } func main() { token, err := generateResetToken(32) // 32 random bytes if err != nil { panic(err) } fmt.Println(token) } ``` Why this is secure: - `crypto/rand` provides cryptographical...Votes: 0GitHub stars: 549
- Golang SecurityThe recommended password hashing algorithm for Go is Argon2id, typically via `golang.org/x/crypto/argon2`. It is preferred over bcrypt, MD5, or SHA-1 for new password hashing. A common baseline is `time=1`, `memory=64MB`, and `threads=4`, with a unique random salt per password.Votes: 0GitHub stars: 549
- Golang TestingUse a table-driven test: define cases as a slice of structs, then loop with `t.Run(...)` so each status case is isolated. ```go package order import ( "testing" ) func TestParseOrderStatus(t *testing.T) { t.Parallel() tests := []struct { name string input string want OrderStatus wantErr bool }{ { name: "paid", input: "paid", want: StatusPaid, wantErr: false, }, { name: "pending", input: "pending", want: StatusPending, wantErr: false, }, { name: "unknown status", inp...Votes: 0GitHub stars: 549
- Golang TestingUnit test the service by depending on an interface, not a concrete DB client. Your service should receive a repository or store interface: ```go type UserStore interface { GetByID(ctx context.Context, id string) (*User, error) } type Service struct { store UserStore } func NewService(store UserStore) *Service { return &Service{store: store} } ``` Then in tests, replace the real DB with a mock or fake implementation: ```go type mockUserStore struct { user *User err error } func (m *mockUserSt...Votes: 0GitHub stars: 549
- Golang TestingUsually no — not directly in the loop body. Why: if you call `assert` inside a plain `for` loop, failures are harder to attribute to a specific case, and one bad case can make the output less clear. In Go, the cleaner pattern is table-driven tests with `t.Run(...)` subtests, then do assertions inside each subtest. Better: ```go func TestSomething(t *testing.T) { tests := []struct { name string input int want int }{ {"one", 1, 2}, {"two", 2, 3}, } for _, tt := range tests { tt := tt t.Run(tt....Votes: 0GitHub stars: 549
- Golang ToolingSet up `golangci-lint` by adding a `.golangci.yml` at your repo root, installing the binary, and running it as part of your normal Go verification flow. Install: ```bash go install github.com/golangci/golangci-lint/cmd/golangci-lint@latest ``` Recommended workflow after edits: 1. `go vet ./...` 2. `goimports -w .` 3. `golangci-lint run ./...` Good linters to enable: - `errcheck` — makes sure errors are not ignored - `staticcheck` — strong bug-finding beyond basic vet checks - `govet` — correc...Votes: 0GitHub stars: 549
- Golang Tooling`gofmt` only formats Go code. `goimports` does that too, and also adds/removes/sorts imports automatically. So in practice: - Use `goimports` for everyday editing and before commit. - Use `gofmt` only if you specifically want formatting without touching imports. If you already use `goimports`, you usually do not need to run `gofmt` separately.Votes: 0GitHub stars: 549
- Golang ToolingTo get real-time Go diagnostics and type errors in Claude Code, use `gopls` through the IDE diagnostics integration. 1. Install `gopls`: ```bash go install golang.org/x/tools/gopls@latest ``` 2. Make sure your Claude Code environment has the `gopls`-backed IDE diagnostics integration available. 3. Use `mcp__ide__getDiagnostics` to surface real-time errors, type issues, and warnings from `gopls`. Recommended Go tooling workflow after edits: - `mcp__ide__getDiagnostics` - `go vet ./...` - `goim...Votes: 0GitHub stars: 549
- Ios App LifecycleUse `SceneDelegate` as the main entry point for UI lifecycle on iOS 13+, and keep `AppDelegate` focused on app-wide setup only. - In `SceneDelegate`, create the `UIWindow`, attach it to the `UIWindowScene`, and start your root coordinator there. - In `AppDelegate`, keep `application(_:didFinishLaunchingWithOptions:)` slim by delegating dependency registration, analytics setup, and push registration to a dedicated `AppBootstrapper`. - For deep links, prefer Universal Links and handle them thro...Votes: 0GitHub stars: 549
- Ios App LifecycleCommon anti-patterns to avoid in the iOS app lifecycle: - Putting too much logic in `AppDelegate`. Keep it slim and move setup and orchestration into a `Bootstrapper` or `AppCoordinator`. - Managing `UIWindow` manually in `AppDelegate` on iOS 13+. Use `SceneDelegate` for window and scene-specific lifecycle handling. - Doing synchronous network or heavy work during app launch. Launch should stay fast; move blocking work off the main thread. - Handling deep links in an ad hoc way. Prefer Univer...Votes: 0GitHub stars: 549
- Ios App LifecycleHere’s a quick-start iOS app lifecycle example for an iOS 13+ app: ```swift import UIKit import BackgroundTasks @main final class AppDelegate: UIResponder, UIApplicationDelegate { private let bootstrapper = AppBootstrapper() func application( _ application: UIApplication, didFinishLaunchingWithOptions launchOptions: [UIApplication.LaunchOptionsKey: Any]? = nil ) -> Bool { bootstrapper.configureAppServices() BackgroundTaskManager.shared.register() return true } } final class SceneDelegate: UIR...Votes: 0GitHub stars: 549
- Ios ArchitectureUse a structure that keeps UI, logic, and navigation separate. For screen-level architecture, MVVM is a strong default: - ViewController/View: renders UI and forwards user events - ViewModel: owns presentation logic, formatting, and view state - Model/Service layer: handles domain data and side effects A good ViewModel should avoid `UIKit` imports unless a platform type is truly unavoidable. It should expose state in a controlled way, such as `private(set)` properties or publishers like `@Pub...Votes: 0GitHub stars: 549
- Ios ArchitectureCommon iOS architecture anti-patterns to avoid: - Putting business logic in `UIViewController`. Keep controllers thin and move logic into a `ViewModel`, `Interactor`, or equivalent layer. - Letting the `ViewModel` depend on `UIKit`. A ViewModel should stay platform-light and focus on state, formatting, and behavior. - Exposing mutable ViewModel state publicly. Prefer `private(set)`, bindings, or publishers so the view can observe state without mutating it directly. - Skipping clear input/outp...Votes: 0GitHub stars: 549
- Ios ArchitectureHere’s a quick-start MVVM + Coordinator example for iOS: ```swift import UIKit import Combine struct LoginViewState { var isLoading = false var errorMessage: String? var isLoggedIn = false } protocol AuthServicing { func login(email: String, password: String) -> AnyPublisher<Bool, Error> } final class LoginViewModel { @Published private(set) var state = LoginViewState() private let authService: AuthServicing private var cancellables = Set<AnyCancellable>() init(authService: AuthServicing) { s...Votes: 0GitHub stars: 549
- Ios Dependency InjectionUse protocol-based initializer injection as the default. Best-practice shape: - Define protocols for dependencies, not concrete classes. - Inject them through `init(...)` so the dependency graph is explicit and easy to test. - Avoid resolving dependencies inside business logic or view models. - Avoid global singletons unless the lifetime is truly app-wide and intentionally scoped. Example: ```swift protocol AnalyticsServiceProtocol { func logEvent(name: String) } final class HomeViewModel { p...Votes: 0GitHub stars: 549
- Ios Dependency InjectionCommon iOS dependency-injection anti-patterns to avoid: - Global singletons as the default for services. They hide dependencies, create shared mutable state, and make tests brittle. - Resolving dependencies inline inside business logic or view models, like calling a container or `resolve()` from the object itself. Prefer passing dependencies in from the outside. - Depending on concrete classes instead of protocols. That tightly couples code and makes mocking or swapping implementations harder...Votes: 0GitHub stars: 549
- Ios Dependency InjectionHere’s a simple quick-start using protocol-based initializer injection first, then Factory for wiring: ```swift import UIKit import Factory protocol AnalyticsServiceProtocol { func logEvent(name: String) } final class AnalyticsService: AnalyticsServiceProtocol { func logEvent(name: String) { print("Logged: \(name)") } } final class HomeViewModel { private let analytics: AnalyticsServiceProtocol init(analytics: AnalyticsServiceProtocol) { self.analytics = analytics } func screenOpened() { anal...Votes: 0GitHub stars: 549
- Ios DeploymentImplement iOS deployment around Fastlane and centralized signing, not manual Xcode steps. Start with `fastlane match` so certificates and provisioning profiles are managed from a private shared repository. That keeps local machines and CI consistent and avoids storing certificates directly in the app repo. In your Xcode build settings, make signing explicit for automated environments. If you are not relying on automatic signing in CI, set `PROVISIONING_PROFILE_SPECIFIER` and related signing v...Votes: 0GitHub stars: 549
- Ios DeploymentCommon iOS deployment anti-patterns to avoid: - Manual CI signing instead of centralized signing management. Prefer `fastlane match`. - Storing certificates or provisioning profiles directly in the app repo. - Manual version/build number bumps instead of automating them with Fastlane, such as `increment_build_number`. - Skipping explicit signing/build configuration in CI, for example not setting `PROVISIONING_PROFILE_SPECIFIER` when manual or CI signing is required. - Shipping without scripte...Votes: 0GitHub stars: 549
- Ios DeploymentA quick-start setup is Fastlane + Match so signing and deployment stay automated. `Fastfile` ```ruby default_platform(:ios) platform :ios do desc "Push a new beta build to TestFlight" lane :beta do setup_ci match(type: "appstore") increment_build_number(xcodeproj: "App.xcodeproj") build_app(scheme: "App") upload_to_testflight(skip_waiting_for_build_processing: true) end desc "Push a new release to the App Store" lane :release do match(type: "appstore") build_app(scheme: "App") upload_to_app_s...Votes: 0GitHub stars: 549
- Ios Design SystemImplement the design system around centralized SwiftUI tokens in `/Theme/`, following Apple’s iOS Human Interface Guidelines. ```swift // Theme/Spacing.swift enum Spacing { static let sm: CGFloat = 8 static let md: CGFloat = 16 static let lg: CGFloat = 24 } ``` Define brand colors in the Asset Catalog and reference them by name: ```swift extension Color { static let appPrimary = Color("AppPrimary") static let appBackground = Color("AppBackground") } ``` Avoid hex colors, `Color.blue`, and oth...Votes: 0GitHub stars: 549
- Ios Design SystemCommon iOS design-system anti-patterns to avoid: - Hardcoded hex colors in SwiftUI. Define brand colors in the Asset Catalog and use `Color("Name")`. - Magic spacing values such as `spacing: 16`. Centralize spacing tokens in `/Theme/` and use values like `Spacing.md`. - Using system colors for brand UI, such as `Color.blue`. Use semantic design tokens like `.appPrimary`. - Scattering typography definitions throughout views. Create shared `Font` extensions and typography tokens. - Duplicating ...Votes: 0GitHub stars: 549
- Ios Design SystemA simple SwiftUI design system: ```text /Theme/ AppColors.swift Spacing.swift AppFonts.swift Assets.xcassets/ AppPrimary.colorset ``` ```swift // Theme/AppColors.swift import SwiftUI extension Color { static let appPrimary = Color("AppPrimary") // Asset Catalog token } ``` ```swift // Theme/Spacing.swift import Foundation enum Spacing { static let sm: CGFloat = 8 static let md: CGFloat = 16 static let lg: CGFloat = 24 } ``` ```swift // Theme/AppFonts.swift import SwiftUI extension Font { stat...Votes: 0GitHub stars: 549
- Ios LocalizationFor modern iOS apps, the best-practice path is: - Use String Catalogs (`.stringcatalog`) in Xcode 15+ as the source of truth for UI text. They give you visual editing, pluralization support, and better missing-translation checks. - Prefer modern localization APIs like `String(localized:)` or `LocalizedStringResource` instead of older `NSLocalizedString` for new code. - Keep `Base` localization complete first, then add additional languages on top of that. - Use built-in pluralization in String...Votes: 0GitHub stars: 549
- Ios LocalizationCommon anti-patterns to avoid in iOS localization: - Using `NSLocalizedString` in new code instead of modern APIs like `String(localized:)` or `LocalizedStringResource` - Manually handling pluralization in app logic instead of using String Catalog plural support - Manually formatting currency, dates, or numbers instead of locale-aware formatting APIs - Storing loose image/string assets outside `.xcassets` - Leaving placeholder or partially translated strings in the app - Adding secondary lang...Votes: 0GitHub stars: 549
- Ios LocalizationHere’s a quick-start example using modern iOS localization with a String Catalog. 1. In Xcode, add a `Localizable.xcstrings` String Catalog. 2. Add a key like `welcome.title`. 3. Provide a Base value such as `Welcome`. 4. Add translations for each supported language. SwiftUI: ```swift import SwiftUI struct WelcomeView: View { var body: some View { VStack(spacing: 12) { Text(String(localized: "welcome.title")) Text( Date.now.formatted( date: .abbreviated, time: .omitted ) ) } .padding() } } ``...Votes: 0GitHub stars: 549
- Ios NavigationUse `NavigationStack` on iOS 16+ and keep a `NavigationPath` when you need programmatic pushes or deep-link routing. Handle incoming URLs at the root `WindowGroup` with `onOpenURL`, parse them safely with `guard let`, validate that the destination content actually exists, then append the matching route to the path so the back stack stays consistent. For Universal Links, configure the `applinks` Associated Domains entitlement and route `NSUserActivity` or URL-based entry points into the same n...Votes: 0GitHub stars: 549
- Ios NavigationCommon iOS navigation anti-patterns to avoid: - Force-unwrapping URL parts or route data instead of validating with `guard let`. - Corrupting the back stack by pushing destinations when the current navigation state is invalid. - Navigating from deep links before checking the target content actually exists. - Mixing ad-hoc navigation state instead of using a consistent `NavigationStack` and `NavigationPath` flow. - Handling deep links too low in the view tree instead of at the root with `onOpe...Votes: 0GitHub stars: 549
- Ios NavigationHere’s a quick-start SwiftUI navigation example using `NavigationStack`, plus a simple deep-link handler at the root: ```swift import SwiftUI enum Route: Hashable { case detail(id: Int) case settings } @main struct MyApp: App { var body: some Scene { WindowGroup { RootView() } } } struct RootView: View { @State private var path = NavigationPath() var body: some View { NavigationStack(path: $path) { List { Button("Open Detail 42") { path.append(Route.detail(id: 42)) } Button("Open Settings") {...Votes: 0GitHub stars: 549
- Ios NetworkingUse `URLComponents` with `URLQueryItem` instead of string interpolation. Example: ```swift var components = URLComponents(string: "https://api.example.com/search")! components.queryItems = [ URLQueryItem(name: "q", value: "iphone 16"), URLQueryItem(name: "page", value: "1") ] let url = components.url! ``` Why: - Safely encodes query parameters - Avoids bugs with spaces, `&`, `?`, and other special characters - Makes optional parameters easier to add/remove If you also need path composition, k...Votes: 0GitHub stars: 549
- Ios NetworkingStore tokens securely in the Keychain, not in `UserDefaults` or hardcoded in code. For requests, inject the token into every `URLRequest` as: `Authorization: Bearer <token>` Good pattern on iOS: - Keep a small auth/token store that reads the current access token from Keychain - Centralize request building so auth headers are added in one place - If you use Alamofire, use a `RequestInterceptor` to attach the bearer token automatically - On `401 Unauthorized`, refresh the token, save the new to...Votes: 0GitHub stars: 549