go
20 lines · 1 tab
Leah Thompson
Jan 2026
1 tab
package api
import (
"encoding/json"
"errors"
"io"
)
func decodeJSON(r io.Reader, dst any) error {
dec := json.NewDecoder(r)
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return err
}
if err := dec.Decode(&struct{}{}); err != io.EOF {
return errors.New("body must contain a single JSON value")
}
return nil
}
1 file · go
Explain with highlit
Large request bodies are where naive code falls over. Instead of io.ReadAll, I decode JSON incrementally with json.Decoder and enable DisallowUnknownFields so unexpected fields fail fast. That becomes a surprisingly strong safety net when you evolve APIs: client typos and version drift surface as clear 400s instead of becoming silently ignored data. I also guard against multiple JSON values by attempting a second decode and expecting io.EOF. Combined with http.MaxBytesReader, this prevents memory blowups and a class of parsing ambiguities. It's a small helper, but it pushes validation into a single choke point so handlers can stay focused on business logic.
Related snips
go
package api
import (
"net/http"
"runtime/debug"
)
Expose build metadata for debugging deploys
go
observability
build
by Leah Thompson
1 tab
ruby
payload = {
sub: user.id,
iss: 'https://auth.example.com',
aud: 'codesnips-api',
exp: 15.minutes.from_now.to_i,
iat: Time.now.to_i,
JWT issuance and verification without common footguns
jwt
authentication
api
by Kai Nakamura
2 tabs
typescript
export interface RetryOptions {
retries: number;
baseMs: number;
maxMs: number;
signal?: AbortSignal;
onRetry?: (attempt: number, delay: number, err: unknown) => void;
Exponential backoff with jitter for retries
typescript
reliability
retry
by codesnips
2 tabs
ruby
module Api
module V1
class UsersController < BaseController
def show
user = User.includes(:profile).find(params[:id])
ETags for conditional requests and caching
rails
caching
http-caching
by Alex Kumar
1 tab
go
package dbutil
import (
"context"
"github.com/jackc/pgconn"
Retry Postgres serialization failures with bounded attempts
go
postgres
transactions
by Leah Thompson
1 tab
graphql
type User {
id: ID!
name: String!
email: String!
posts: [Post!]!
createdAt: String!
GraphQL API with Spring Boot
java
graphql
spring-boot
by David Kumar
3 tabs
Share this code
Here's the card — post it anywhere.