Logo: Go Standard Library

Go Standard Library

Communautéit
v0lka
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.

Iwwersiicht

Editeurv0lka
Repositoryskills
Skill-Nummgo-standard-library
Stären
28
Forks
1
Matgeliwwert Dateien
Nëmmen Instruktiounen
LizenzMIT
Linken
  • Instruktiounen am Markdown-Format

    Eng SKILL.md-Datei, déi de Modell bei Bedarf luet, soudatt nëmmen Token ufalen, wann eng Ufro tatsächlech dozou passt.

  • Funktionéiert mat all LLM

    KI-Skills si reng Markdown, keen ubidderspezifesche Code. Dofir funktionéiert dëse Skill mat GPT, Claude, Gemini, Grok oder engem lokale Modell.

  • Alles an den Instruktiounen

    Alles, wat de Modell brauch, steet an den Instruktiounen — keng zousätzlech Dateien ze synchroniséieren.

  • Open Source

    v0lka huet de Skill op GitHub verëffentlecht. Liest de Quelltext, ier Dir de Skill installéiert.

Installatioun

Installéiert de KI-Skill Go Standard Library an TypingMind, fir e mat all LLM ze benotzen, oder setzt en an en anere KI-Agent an, deen SKILL.md liest.

1

An TypingMind installéieren

TypingMind installéiert e Skill direkt aus sengem GitHub-Dossier — dobäi gëtt SKILL.md gelies, d'Ressourcedateie gi gebëndelt an d'Resultat gëtt lokal gespäichert.

  1. Maacht d'App op a gitt op Plugins → Skills.
  2. Wielt „Vu GitHub installéieren“.
  3. Pecht d'URL vum Skill-Dossier, déi hei drënner steet, an a bestätegt d'Installatioun.
    https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-standard-library
  4. Aktivéiert de Skill an all Chat, an deem Dir e benotze wëllt.
Plugins → Skills → Skill derbäisetzen → Iwwer eng GitHub-URL. Pecht dann d'URL vum Dossier an a klickt op Weider.
2

An engem anere KI-Agent installéieren

All KI-Agent, deen d'Format Agent Skills liest, kann dëse Skill benotzen — kopéiert den Dossier an d'Skill-Verzeechnes vun deem KI-Agent.

Claude Code — .claude/skills
git clone --depth 1 https://github.com/v0lka/skills.git /tmp/skills
mkdir -p .claude/skills
cp -r /tmp/skills/development/idiomatic-go/go-standard-library .claude/skills/go-standard-library
Start Claude Code nom Kopéieren nei, fir datt den neie Skill erkannt gëtt.

An TypingMind benotzen

Aktivéiert Go Standard Library an engem Chat vun TypingMind, an de Modell iwwerhëlt de Rescht. Den Numm an d'Beschreiwung stinn am System-Prompt. Soubal eng Ufro dozou passt, luet de Modell déi komplett Instruktioune selwer — Dir musst de Skill ni manuell opruffen, an et fale keng Token un, bis en tatsächlech benotzt gëtt.

De Modell luet Go Standard Library automatesch, soubal eng Ufro dozou passt.

Funktionéiert mat all KI-Modell

KI-Skills si reng Markdown-Instruktiounen amplaz vun ubidderspezifeschem Code. Dofir ass Go Standard Library net un de Modell gebonnen, fir deen de Skill geschriwwe gouf. Installéiert en eemol an TypingMind a benotzt e mat GPT-5, Claude, Gemini, Grok, DeepSeek, Mistral, Llama oder engem lokale Modell, deen Dir selwer bedreift — alles mat Ären eegenen API-Schlësselen.

  • Gëtt nëmme gelueden, wann et néideg ass

    De System-Prompt enthält nëmmen den Numm an d'Beschreiwung. D'Instruktioune gi bei der éischter passender Ufro gelueden, soudatt en onbenotzte Skill näischt kascht.

  • De Modell am lafende Chat wiesselen

    Well de Skill aus Instruktiounen amplaz vu Code besteet, funktionéiert en och no engem Modellwiessel — den nächste Modell liest déi selwecht SKILL.md-Datei.

Skill-Instruktiounen

Dëst ass den Inhalt vu SKILL.md, deen de Modell luet. Liest e virun der Installatioun — e Skill besteet aus Instruktiounen, déi Äre Modell befollegt.

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.

go
// 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.

go
// 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.

go
// 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.

go
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) or t.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.

go
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.

go
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:

MethodDefaultGuidance
SetMaxOpenConnsUnlimitedMust set. Match what the DB can handle.
SetMaxIdleConns2Increase for high-concurrency workloads to avoid frequent reconnects.
SetConnMaxIdleTimeUnlimitedSet to release connections after traffic bursts.
SetConnMaxLifetimeUnlimitedSet when connecting through a load balancer.
go
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).

go
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 type fails at runtime. Use a pointer or sql.NullXXX type for nullable columns.

go
// Option A: pointer
var department *string
err := rows.Scan(&department, &age) // department is nil if NULL

// Option B: sql.NullString (preferred -- clearer intent)
var department sql.NullString
err := rows.Scan(&department, &age)
if department.Valid {
    fmt.Println(department.String)
}

Available null types: sql.NullString, sql.NullBool, sql.NullInt32, sql.NullInt64, sql.NullFloat64, sql.NullTime.

4.5 Check rows.Err After Iteration

Rule: rows.Next() can return false either because all rows were consumed OR because an error occurred preparing the next row. Always check rows.Err() after the loop.

go
for rows.Next() {
    if err := rows.Scan(&department, &age); err != nil {
        return err
    }
}
if err := rows.Err(); err != nil {
    return err
}

5. Closing Transient Resources (#79)

Rule: Any struct implementing io.Closer must be closed. Use defer immediately after the creation/error-check.

5.1 HTTP Response Body

  • Always close resp.Body when err == nil, even if you don't read it.
  • Closing without reading may prevent TCP connection reuse. To preserve keep-alive, drain the body first.
go
resp, err := client.Get(url)
if err != nil {
    return err
}
defer resp.Body.Close()

// If you don't need the body but want keep-alive:
_, _ = io.Copy(io.Discard, resp.Body)

Note: On the server side, the request body is closed automatically. No action needed.

5.2 sql.Rows

Forgetting to close sql.Rows leaks a database connection back to the pool.

go
rows, err := db.QueryContext(ctx, query)
if err != nil {
    return err
}
defer rows.Close()

5.3 os.File

Not closing os.File delays release until GC. For writable files, the close error may surface a buffered write failure -- propagate it.

go
// Read-only: log close errors
f, err := os.Open(filename)
if err != nil {
    return err
}
defer func() {
    if err := f.Close(); err != nil {
        log.Printf("failed to close file: %v", err)
    }
}()

// Writable: propagate close errors via named return
func writeToFile(filename string, content []byte) (err error) {
    f, err := os.Create(filename)
    if err != nil {
        return err
    }
    defer func() {
        closeErr := f.Close()
        if err == nil {
            err = closeErr
        }
    }()
    _, err = f.Write(content)
    return
}

If durability matters, call f.Sync() before close. Then close errors can be safely ignored.


6. Return After HTTP Error Reply (#80)

Rule: http.Error does NOT stop handler execution. Always return immediately after it.

go
// BAD: execution continues after error reply
func handler(w http.ResponseWriter, req *http.Request) {
    err := foo(req)
    if err != nil {
        http.Error(w, "foo", http.StatusInternalServerError)
    }
    // This runs even on error -- may panic on nil pointer, or write duplicate response
    result := bar(req)
    w.Write(result)
}

// GOOD: return after error reply
func handler(w http.ResponseWriter, req *http.Request) {
    err := foo(req)
    if err != nil {
        http.Error(w, "foo", http.StatusInternalServerError)
        return
    }
    result := bar(req)
    w.Write(result)
}

This applies to any function that writes an HTTP error: http.Error, w.WriteHeader, json.NewEncoder(w).Encode, etc. Missing return causes duplicate writes and a superfluous WriteHeader warning.


7. Default HTTP Client and Server (#81)

7.1 HTTP Client

Rule: Never use http.DefaultClient, http.Get(), http.Post(), or &http.Client{} in production. They have no timeouts -- requests can hang forever.

go
// GOOD: production HTTP client
client := &http.Client{
    Timeout: 5 * time.Second,
    Transport: &http.Transport{
        DialContext: (&net.Dialer{
            Timeout: time.Second,
        }).DialContext,
        TLSHandshakeTimeout:   time.Second,
        ResponseHeaderTimeout:  time.Second,
        MaxIdleConnsPerHost:    100,
        IdleConnTimeout:        90 * time.Second,
    },
}

Key timeouts:

TimeoutCovers
net.Dialer.TimeoutTCP dial
Transport.TLSHandshakeTimeoutTLS handshake
Transport.ResponseHeaderTimeoutWaiting for response headers
Client.TimeoutEntire request (dial through body read)

Connection pooling: Default MaxIdleConnsPerHost is 2. For high-throughput to a single host, increase it to avoid constant reconnection overhead.

7.2 HTTP Server

Rule: Never use &http.Server{}, http.ListenAndServe(), or http.Serve() without timeouts in production. Clients can exploit missing timeouts to exhaust resources.

go
// GOOD: production HTTP server
srv := &http.Server{
    Addr:              ":8080",
    ReadHeaderTimeout: 500 * time.Millisecond,
    ReadTimeout:       time.Second,
    IdleTimeout:       time.Second,
    Handler:           http.TimeoutHandler(handler, 5*time.Second, "request timeout"),
}

Key timeouts:

TimeoutCovers
ReadHeaderTimeoutReading request headers. Must set to prevent Slowloris attacks.
ReadTimeoutReading entire request (headers + body).
http.TimeoutHandlerHandler execution time. Returns 503 on timeout and cancels the handler's context.
IdleTimeoutKeep-alive idle time. Falls back to ReadTimeout if unset.

Prefer http.TimeoutHandler over the older WriteTimeout field: it returns a proper 503 status, cancels the handler context, and has consistent behavior regardless of TLS.


Quick Reference

MistakeRule
#75 Time durationNever pass bare integers; use time.Second, time.Millisecond, etc.
#76 time.After leakUse time.NewTimer + Reset in loops/repeated code paths
#77a Embedded JSONEmbedded types can hijack marshal/unmarshal; prefer named fields
#77b Monotonic clockUse Equal() or Truncate(0) for time comparison after JSON round-trip
#77c Map of anyAll JSON numbers become float64; assert correctly or use a struct
#78a sql.OpenFollow with Ping/PingContext to verify connectivity
#78b Connection poolSet MaxOpenConns, MaxIdleConns, ConnMaxIdleTime, ConnMaxLifetime
#78c Prepared stmtsUse Prepare for repeated queries and untrusted input
#78d Null valuesUse *T or sql.NullXXX for nullable columns
#78e Row iterationAlways check rows.Err() after the rows.Next() loop
#79 Close resourcesdefer Close() for resp.Body, sql.Rows, os.File, and all io.Closer
#80 Return after errorhttp.Error does not stop execution; always return after it
#81a HTTP clientSet dial, TLS, header, and overall timeouts; tune MaxIdleConnsPerHost
#81b HTTP serverSet ReadHeaderTimeout; use http.TimeoutHandler; set IdleTimeout

Heefeg gestallte Froen

Wat mécht de KI-Skill 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 packa...

Firwat Go Standard Library op TypingMind benotzen?

Well Dir en eemol installéiert a mat all Modell benotze kënnt. Go Standard Library besteet aus einfachem Markdown amplaz vun ubidderspezifeschem Code. Dee selwechte Skill funktionéiert also mat GPT-5, Claude, Gemini, Grok oder engem lokale Modell – an Dir kënnt de Modell matzen am Chat wiesselen, ouni datt de Skill ophält ze funktionéieren. TypingMind benotzt Är eegen API-Schlësselen, sou datt Dir d'Ubidder direkt bezuelt, amplaz en Abonnement pro Benotzerplaz ze bezuelen. Är Skills a Chats bleiwen an Ärem eegene Späicher.

Wéi installéieren ech Go Standard Library an TypingMind?

Maacht an TypingMind Plugins → Skills → Vu GitHub installéieren op a setzt https://github.com/v0lka/skills/tree/main/development/idiomatic-go/go-standard-library an. TypingMind liest d'Datei SKILL.md an installéiert de Skill, deen Dir pro Chat aktivéiere kënnt.

Wéi eng KI-Modeller kënnen Go Standard Library benotzen?

All Modell, deen Dir an TypingMind verbënnt. KI-Skills sinn einfach Markdown-Instruktiounen an net ubidderspezifesche Code. Dofir kënne GPT, Claude, Gemini, Grok a lokal Modeller dëse Skill lueden, wann eng Ufro dozou passt.

Wéi vill KI-Modeller kann ech mat Go Standard Library benotzen?

Esou vill wéi Dir wëllt. Soulaang e Modell Skills ënnerstëtzt, kënnt Dir Go Standard Library domat benotzen – zum Beispill mat GPT, Claude, Gemini, Grok, DeepSeek, Mistral oder Llama – alles op TypingMind mat Ären eegenen API-Schlësselen.

Ass de KI-Skill Go Standard Library gratis?

Jo. v0lka huet de Skill ënner der Lizenz MIT op GitHub publizéiert. Dir bezuelt nëmmen Ären eegene KI-Ubidder fir d'Token, déi Dir benotzt.

Wat si KI-Skills?

E KI-Skill ass e weiderverwendbare Pak vun Instruktiounen, deen engem KI-Modell bäibréngt, wéi en eng bestëmmt Aufgab erfëllt. E follegt dem oppenen Agent Skills-Format: eng Datei SKILL.md mat engem Numm an enger Beschreiwung, plus all Scripten, Virlagen oder Referenzdateien, déi de Modell eventuell brauch. De Modell liest d'Instruktiounen eréischt, wann Är Ufro zum Skill passt. En installéierte Skill kascht also näischt, bis e benotzt gëtt.

Wéi ënnerscheede sech KI-Skills vu Plugins oder MCP-Serveren?

E Plugin oder MCP-Server gëtt engem Modell nei Tools, déi en opruffe kann – Code, deen iergendwou leeft an e Resultat zeréckgëtt. E KI-Skill gëtt dem Modell dogéint Wëssen an eng Virgoensweis: wéi en eng Aufgab ugeet, wéi eng Schrëtt e maache soll a wéi eng gutt Ausgab ausgesäit. Skills bestinn aus einfachem Markdown, brauche kee Server, keen API-Schlëssel a kee Lafzäitëmfeld a funktionéiere mat all Modell.

Alleguer weisen

Elo Ären eegene KI-Aarbechtsberäich ariichten

Abonnéiert Iech op eisen Newsletter, fir iwwer nei Funktiounen an zukünfteg Gewënnspiller informéiert ze ginn 👇