Add Go patterns cheat sheet
🤖 Generated with [Claude Code](https://claude.ai/code) Co-Authored-By: Claude <noreply@anthropic.com>
This commit is contained in:
parent
d7e7e81ab9
commit
51a7d9c7c8
1 changed files with 77 additions and 0 deletions
77
go-cheatsheet.md
Normal file
77
go-cheatsheet.md
Normal file
|
@ -0,0 +1,77 @@
|
||||||
|
# Go Patterns Cheat Sheet
|
||||||
|
|
||||||
|
## Defer - Cleanup Pattern
|
||||||
|
```go
|
||||||
|
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
|
||||||
|
```go
|
||||||
|
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
|
||||||
|
```go
|
||||||
|
func startMiningTicker() {
|
||||||
|
ticker := time.NewTicker(1 * time.Minute)
|
||||||
|
defer ticker.Stop()
|
||||||
|
|
||||||
|
for {
|
||||||
|
select {
|
||||||
|
case <-ticker.C:
|
||||||
|
updateMiningValue()
|
||||||
|
}
|
||||||
|
}
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- `time.NewTicker()` creates repeating timer
|
||||||
|
- `select` waits for channel events
|
||||||
|
- `<-ticker.C` receives from ticker's channel
|
||||||
|
- Common pattern for background jobs
|
||||||
|
|
||||||
|
## Database Scanning into Structs
|
||||||
|
```go
|
||||||
|
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
|
||||||
|
```go
|
||||||
|
_, err = db.Exec("INSERT INTO mining (timestamp, value, rate) VALUES (?, ?, ?)", now, newValue, latest.Rate)
|
||||||
|
```
|
||||||
|
- `_` = blank identifier, discards unwanted return values
|
||||||
|
- `db.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
|
||||||
|
```go
|
||||||
|
func handler(w http.ResponseWriter, r *http.Request) {
|
||||||
|
// w = where response goes
|
||||||
|
// r = incoming request data
|
||||||
|
fmt.Fprintf(w, "response")
|
||||||
|
}
|
||||||
|
```
|
||||||
|
- `w` writes back to client
|
||||||
|
- `r` contains request info
|
||||||
|
- Common to use `fmt.Fprintf(w, ...)` for simple responses
|
Loading…
Add table
Reference in a new issue