
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
2.2 KiB
2.2 KiB
Go Patterns Cheat Sheet
Defer - Cleanup Pattern
initDB()
defer db.Close() // Runs when function exits, no matter how
- Schedules function to run when surrounding function returns
- Executes in LIFO order if multiple defers
- Great for resource cleanup (files, connections, etc.)
Formatted Output to HTTP
fmt.Fprintf(w, "%d", rng.Intn(1000))
fmt.Fprintf
= formatted print to a writer (not stdout)w
= HTTP response writer%d
= format placeholder for integers- Alternative:
fmt.Fprint(w, value)
for no formatting
Ticker + Select for Scheduled Tasks
func startMiningTicker() {
ticker := time.NewTicker(1 * time.Minute)
defer ticker.Stop()
for {
select {
case <-ticker.C:
updateMiningValue()
}
}
}
time.NewTicker()
creates repeating timerselect
waits for channel events<-ticker.C
receives from ticker's channel- Common pattern for background jobs
Database Scanning into Structs
type MiningRecord struct {
ID int `json:"id"`
Timestamp time.Time `json:"timestamp"`
Value float64 `json:"value"`
Rate float64 `json:"rate"`
}
var latest MiningRecord
err := db.QueryRow("SELECT id, timestamp, value, rate FROM mining ORDER BY timestamp DESC LIMIT 1").
Scan(&latest.ID, &latest.Timestamp, &latest.Value, &latest.Rate)
Scan()
copies SQL results into Go variables- Order matters: first column → first Scan argument
- Use
&
to pass addresses so Scan can write to them - Struct tags (
json:"id"
) control JSON serialization
Blank Identifier for Ignoring Values
_, err = db.Exec("INSERT INTO mining (timestamp, value, rate) VALUES (?, ?, ?)", now, newValue, latest.Rate)
_
= blank identifier, discards unwanted return valuesdb.Exec()
returns(sql.Result, error)
- We only care about the error, so ignore the Result
- Go requires this instead of leaving variables unused
HTTP Handler Pattern
func handler(w http.ResponseWriter, r *http.Request) {
// w = where response goes
// r = incoming request data
fmt.Fprintf(w, "response")
}
w
writes back to clientr
contains request info- Common to use
fmt.Fprintf(w, ...)
for simple responses