go-standard-library
Guides the agent to avoid common Go standard library mistakes when writing or reviewing Go code. Covers time.Duration misuse, time.After memory leaks, JSON handling pitfalls (type embedding, monotonic clock, map of any), SQL mistakes (sql.Open, connection pooling, prepared statements, null values, row iteration errors), closing transient resources (HTTP body, sql.Rows, os.File), missing return after HTTP error replies, and using default HTTP client/server without timeouts. Use when writing, reviewing, or refactoring code that uses the time, encoding/json, database/sql, net/http, or os packages.
v0lka · Static checks on file
Installation
Read the source and dependencies before running a command. Copying does not install or execute anything.
npx skills add v0lka/skills --skill go-standard-libraryAbout this skill
name: go-standard-library description: > Guides the agent to avoid common Go standard library mistakes when writing or reviewing Go code. Covers time.Duration misuse, time.After memory leaks, JSON handling pitfalls (type embedding, monotonic clock, map of any), SQL mistakes (sql.Open, connection pooling, prepared statements, null values, row iteration errors), closing transient resources (HTTP body, sql.Rows, os.File), missing return after HTTP error replies, and using default HTTP client/server without timeouts. Use when writing, reviewing, or refactoring code that uses the time, encoding/json, database/sql, net/http, or os packages.
Go Standard Library
Rules and patterns for correct use of Go's standard library based on common mistakes #75-#81.
1. Time Duration (#75)
Rule: Never pass a bare integer to functions accepting time.Duration. Always use the time API constants.
time.Duration is nanoseconds as int64. Passing 1000 means 1000 nanoseconds (1 microsecond), not 1 second.
// BAD: 1000 nanoseconds, not 1 second
ticker := time.NewTicker(1000)
// GOOD: explicit duration units
ticker := time.NewTicker(time.Second)
ticker := time.NewTicker(1000 * time.Millisecond)
This applies to all functions/methods accepting time.Duration: time.NewTicker, time.NewTimer, time.Sleep, time.After, context.WithTimeout, etc.
2. time.After Memory Leaks (#76)
Rule: Never use time.After inside a loop or any repeatedly-called function (HTTP handler, Kafka consumer, etc.). Use time.NewTimer with Reset instead.
Each time.After call allocates ~200 bytes that cannot be freed until the timer expires. In a hot loop, this causes unbounded memory growth.
// BAD: leaks memory -- each iteration allocates a timer that lives for 1 hour
func consumer(ch <-chan Event) {
for {
select {
case event := <-ch:
handle(event)
case <-time.After(time.Hour):
log.Println("warning: no messages received")
}
}
}
// GOOD: reuse a single timer
func consumer(ch <-chan Event) {
timerDuration := time.Hour
timer := time.NewTimer(timerDuration)
defer timer.Stop()
for {
timer.Reset(timerDuration)
select {
case event := <-ch:
handle(event)
case <-timer.C:
log.Println("warning: no messages received")
}
}
}
time.After is fine for one-shot use outside loops.
3. JSON Handling (#77)
3.1 Type Embedding Hijacks Marshaling
Rule: If an embedded type implements json.Marshaler or json.Unmarshaler, the parent struct silently inherits that behavior, overriding the default field-by-field marshaling.
time.Time implements json.Marshaler. Embedding it causes the entire struct to marshal as just the time value, dropping all other fields.
// BAD: marshals as "2021-05-18T21:15:08Z" -- ID is silently lost
type Event struct {
ID int
time.Time
}
// GOOD: use a named field
type Event struct {
ID int
Time time.Time
}
When reviewing: flag any embedded type that implements json.Marshaler/json.Unmarshaler (e.g., time.Time, encoding.TextMarshaler implementors). Prefer named fields unless the embedding is intentional and a custom MarshalJSON is defined on the parent.
3.2 Monotonic Clock Breaks Equality
Rule: time.Now() includes a monotonic clock reading. JSON marshal/unmarshal strips it. Comparing the original and unmarshaled structs with == returns false.
t := time.Now()
event1 := Event{Time: t}
b, _ := json.Marshal(event1)
var event2 Event
_ = json.Unmarshal(b, &event2)
event1 == event2 // false -- monotonic component differs
Fixes:
- Compare time fields with
time.Time.Equal()(ignores monotonic component). - Strip monotonic before storing:
t.Truncate(0)ort.Round(0). - For tests, use
t.UTC().Truncate(0)to normalize both timezone and monotonic.
3.3 Map of any: Numerics Are float64
Rule: When unmarshaling JSON into map[string]any, all numeric values become float64 -- even integers. Incorrect type assertions (e.g., to int) cause panics.
var m map[string]any
json.Unmarshal([]byte(`{"id": 32}`), &m)
// m["id"] is float64(32), NOT int
// BAD: panics at runtime
id := m["id"].(int)
// GOOD: assert to float64, then convert
id := int(m["id"].(float64))
Prefer unmarshaling into a concrete struct when the schema is known.
4. SQL Mistakes (#78)
4.1 sql.Open Does Not Connect
Rule: sql.Open may only validate arguments without establishing a connection. Always follow it with db.Ping() or db.PingContext() to verify the database is reachable.
db, err := sql.Open("mysql", dsn)
if err != nil {
return err
}
if err := db.PingContext(ctx); err != nil {
return err
}
4.2 Connection Pool Configuration
Rule: *sql.DB is a connection pool, not a single connection. For production, always configure these parameters:
| Method | Default | Guidance |
|---|---|---|
SetMaxOpenConns | Unlimited | Must set. Match what the DB can handle. |
SetMaxIdleConns | 2 | Increase for high-concurrency workloads to avoid frequent reconnects. |
SetConnMaxIdleTime | Unlimited | Set to release connections after traffic bursts. |
SetConnMaxLifetime | Unlimited | Set when connecting through a load balancer. |
db.SetMaxOpenConns(25)
db.SetMaxIdleConns(25)
db.SetConnMaxIdleTime(5 * time.Minute)
db.SetConnMaxLifetime(1 * time.Hour)
4.3 Use Prepared Statements
Rule: Use db.Prepare / db.PrepareContext for repeated queries and any query built from untrusted input (SQL injection defense).
stmt, err := db.PrepareContext(ctx, "SELECT * FROM orders WHERE id = ?")
if err != nil {
return err
}
defer stmt.Close()
rows, err := stmt.QueryContext(ctx, id)
4.4 Null Values
Rule: Scanning a SQL NULL into a non-pointer Go