v1.63.12026-11-04
GoFr v1.63.1 是一个修复版本,解决了两处隐患。
其一,EnableOAuth 此前传入 0 或负数的刷新间隔会直接返回 nil,随后后台刷新协程在 time.NewTicker(0) 上抛出 non-positive interval for NewTicker,进程刚启动就整个崩掉。现在这类参数与非法 JWKS URL 一样被拦下:返回带包装的错误、记录 OAuth 已禁用且不挂载中间件,正常的正数间隔行为不变。建议启动时检查返回值,宁可中止启动也不要裸奔:
``go
if err := app.EnableOAuth("https://idp.example.com/.well-known/jwks.json", 600); err != nil {
app.Logger().Fatal(err) // 启动失败就停下来,而不是在没有认证的情况下继续运行
}
`
其二,只要存在 static/openapi.json,GoFr 就会注册一条 GET /.well-known/{name} 兜底路由,把目录下所有嵌入文件——包括 files.go 这类实现文件——都对外公开,还会挤占应用自定义的同名路由。现在改为启动时枚举 Swagger UI 静态资源,按 .css、.html、.ico、.js、.png 逐个注册,嵌入的实现文件不再路由、返回 404,/.well-known/security.txt 等自有路由也能正常生效。SwaggerUIHandler` 签名未变,直接调用不受影响。
v1.63.02026-11-02
GoFr v1.63.0 更新
新增 SQL 与 Redis 参数脱敏开关 DBREDACTARGS、REDISREDACTARGS,把绑定参数和键值打码成 *****,参数数量与日志结构保持不变,避免 PII 和令牌外泄。
接入托管 Redis 现在只需一个 REDISURL,rediss:// 自动启用 TLS 并校验主机;URL 优先,与之冲突的 REDISHOST 等配置会被忽略并告警。REDISPOOLSIZE、各类超时参数可与 URL 配合使用。
service.RetryConfig 补齐了退避策略、Retry-After 处理、幂等方法限制和重试预算等可选字段,此前固定间隔立即重试、连 POST 也重放,慢上游容易引发重试风暴;字段留空则维持原行为。
RBAC 方面,角色声明为数组时此前匹配不到任何角色、一律 403,现已按数组逐项授权;新增 permissionsClaimPath 可直接从 token 的 scope 等声明授权。configs/rbac.json 是手工维护的路由副本,启动时会对照真实路由检查,发现未覆盖、多余或部分覆盖的规则,由 GOFRRBACROUTE_CHECK 决定警告、拒绝启动还是关闭。
另外新增 DBCONNECTTIMEOUT 限制数据库连接耗时,并为指标序列设上限,溢出统一归入 unmatched,防止扫描路径撑爆监控后端。
v1.62.02026-10-01
Release v1.62.0
🚀 Features
🔹 Google Pub/Sub Flow Control
Three new configs control how many messages a Google Pub/Sub subscriber pulls at once. They are applied to the subscription before Receive:
| config | description | default |
|---|---|---|
| GOOGLEMAXOUTSTANDING_MESSAGES | Most unacknowledged messages held at once. A negative value means no limit. | 1000 |
| GOOGLEMAXOUTSTANDING_BYTES | Most unacknowledged bytes held at once. A negative value means no limit. | 1000000000 (1 GB) |
| GOOGLENUMGOROUTINES | Number of StreamingPull streams. This is not handler concurrency: GoFr delivers one message at a time per topic, so raising it does not raise throughput. | 10 |
The defaults match the SDK's own, so leaving these configs unset keeps the current behavior. An unset, zero or non-integer value uses the default, and a non-integer value is also logged as an error. The defaults are exported as google.DefaultMaxOutstandingMessages, DefaultMaxOutstandingBytes and DefaultNumGoroutines, and the same fields are on google.Config. Query is a one-shot read and does not use these configs.
🔹 Keyless Trace Export to Google Cloud
TRACEEXPORTER=gcp sends spans directly to Google Cloud's Telemetry (OTLP) API using Application Default Credentials. On Cloud Run, traces reach Cloud Trace with an IAM role alone: no key file and no Collector sidecar. Tokens refresh on their own, which a static TRACERHEADERS value can't do.
``go
import _ "gofr.dev/pkg/gofr/traces/exporters/gcp"
`
`
TRACE_EXPORTER=gcp
`
Grant the service account roles/telemetry.tracesWriter. It is the least-privilege role that carries telemetry.traces.write, the permission this endpoint checks. roles/telemetry.writer and roles/cloudtrace.agent also carry it, but they grant more besides. With user credentials instead of a service account, also set GOOGLECLOUDQUOTAPROJECT. The exporter is its own module, so gofr.dev gains no Google dependencies. The module also sets the gcp.projectid resource attribute from the ambient credentials, falling back to GOOGLECLOUDPROJECT.
🔧 Enhancements
🔹 Trace Exporter Registry
Trace exporters now register themselves, the same way metrics exporters already do. A vendor exporter can live in its own module instead of pulling its SDK into gofr.dev. Also in this change:
- The trace resource reads OTELRESOURCEATTRIBUTES and records frameworkversion. service.name still comes from APPNAME.
- Spans are flushed when the app shuts down.
- If an exporter can't be built, the app starts with a NeverSample provider instead of crashing, so X-Correlation-ID still carries a real trace ID.
🔹 Build Tags to Leave Out Unused Dependencies
Six opt-in build tags drop code a service doesn't use. A build that sets none of them is unchanged.
| tag | leaves out |
|---|---|
| gofr_nosqldrivers | the blank-imported SQL drivers |
| gofr_nopubsub | the Kafka, Google and MQTT clients |
| gofr_nographql | graphql-go and gqlparser |
| gofr_nogrpc | the gRPC server, reflection, health and recovery middleware |
| gofr_nodgraph | the Dgraph migrator |
| gofr_nootlp | the OTLP trace and metric transports |
`sh
go build -tags gofrnosqldrivers,gofrnopubsub,gofr_nographql ./...
`
A minimal service built with those three tags is 41.26 MB instead of 57.10 MB (−27.7%) and compiles 554 packages instead of 831.
⚡ Performance
| path | before | after |
|---|---:|---:|
| trie router, static route (100 routes) | 14 allocs, 1072 B, ~570 ns | 8 allocs, 536 B, ~264 ns |
| request log line | 10 allocs | 8 allocs |
- Router: the middleware chain for each route is built once and reused, instead of being rebuilt on every request.
- Logging: the request-log path no longer wraps each entry in a one-element slice. The output bytes are identical.
🛠️ Fixes
- Auth Could Start Disabled — If the RBAC config couldn't be loaded, the app still started and served every route with no role checks. The only sign was one log line. EnableBasicAuth (no credentials, or an odd number of arguments) and EnableOAuth (a bad JWKS URL) failed the same way. All three now return an error, so the app can refuse to start: if err := app.EnableRBAC(path); err != nil { app.Logger().Fatalf("%v", err) }.
- Retries After the Caller Gave Up — RetryConfig kept retrying after the caller's context was done. Each of those attempts failed immediately, yet each was logged and recorded as a 503. In one case a single closed health page produced 28 of them in 0 ms. Retrying now stops once the context is done.
- Circuit Breaker Opened by Cancellations — When a caller cancelled its own request, the breaker counted it as an upstream failure, so callers going away could open the breaker for everyone. Those cancellations are no longer counted, and they no longer reset the failure count either.
- New Connection for Every Health Check — The health-check response body was closed without being read, so net/http never reused the connection. Every check opened a new TCP connection, plus a new TLS handshake over TLS. The body is now drained.
- ClickHouse Durations Were ~0µs — Exec, Select and AsyncInsert took their start time after the call had already returned. The appclickhousestats histogram, the log duration and the span attribute now measure the real call.
- Cassandra and ScyllaDB Swallowed Query Errors — QueryWithCtx never closed the gocql iterator, and closing it is the only place gocql reports a failed query. So a failed query looked like an empty result. The error is now returned.
- Dgraph Mutate Didn't Persist — The transaction was committed only if the caller had set CommitNow. Otherwise nothing was written, the error was nil, and the transaction stayed open on the server. Mutate now commits.
- GCP Metrics Exporter Stopped Exporting — Google rejects any request with more than 200 points. A long-running process eventually grew past that, and from then on every collection was lost. Exports are now split into requests of at most 200 points.
- Kafka Query Held a Timer for 30s — A Query whose caller set no deadline got a 30s read timeout whose cancel func was thrown away. So every such query left a timer and a child context alive for the full 30s after it returned. The timeout is now cancelled as soon as the read returns.
- Event Hub Health Probe Leak — Against a broker that accepts a connection but never answers, every health poll left another goroutine stuck. At most one probe runs at a time now.
- GCS, FTP and Azure File Stores Raced on Reconnect — When the first connect failed, the background retry wrote the connection fields while requests read them, with no lock. GCS Stat, Open, ReadDir, Remove and Rename (and Azure Stat/Remove on a directory) also panicked if called before the store connected. Connection state is now guarded, a store that isn't connected yet returns its "not initialized" error, and a redundant connection from a concurrent Connect is closed instead of leaked.
- WebSocket Stack Overflow — The handler's context was set as its own parent, so .Done(), or a .Value() lookup for any other key, overflowed the stack. A data race on c.Context between the request goroutine and App.WebSocket is fixed too.
- Typed-Nil Pub/Sub Client — When kafka.New or google.New rejected a config, the typed nil they returned passed != nil checks, and a health check then called a method on it. It is now filtered out, including in GetPublisher() and GetSubscriber(), and isNil no longer panics.
- EnableMCP Exited the Process — A busy MCP port triggered Fatalf during setup, which skipped every shutdown hook. The port is now claimed with net.Listen when Run` starts,
v1.61.02026-09-17
GoFr v1.61.0 加入 QUERY 方法(RFC 10008):查询改放请求体,绕开 GET 的 URL 长度限制,入站路由与服务客户端均可用;缺 Content-Type 返 400、无法解码返 415(新增 ErrorUnsupportedMediaType),客户端侧 QUERY 同享熔断与重试,熔断器遇到未知方法改为报错,不再静默返回 nil。健康端点 /.well-known/health 新增 AddReadinessCheck,检查未过即返 503,K8s 就绪探针不再把流量发给依赖未就绪的 Pod;支持多个检查按序执行、首个失败即定结果,也可用 gofr.ReplaceFrameworkChecks() 替换框架自带检查。新增 METRICSCARDINALITYLIMIT 限制指标基数,超限序列并入 otel.metric.overflow;appcircuitopen_count 记录熔断实际跳闸次数。Azure Event Hub 健康检查从空壳改为真实连通性探测,2 秒上限,输出 UP/DOWN 及 backend 等字段。健康检查改为并发执行,单次探测由 1605ms 降到 401ms,20 个并发共享一次结果、后端调用从 80 次降到 4 次;检查抛 panic 会标记为 DOWN 而非拖垮进程。
v1.60.12026-09-02
v1.60.1 修了一个静默丢数据的大问题:GCP 要求 prometheus_target 必须带 location 和 instance,而项目里从未提供 instance,等于所有指标点都被 Google 服务端悄悄丢弃——推送认证照样成功、错误也进不了 otel.SetErrorHandler,线上毫无察觉。现在用 resource.WithHostID() 补上 host.id,启动时解析不到 location 会给出警告;新增 RegisterResourceDetector 和 Config.Resource(均为 Experimental),厂商子模块可以在不引入云 SDK 的前提下补齐字段,升级完全兼容。另外,tracing 中间件的 headerCarrier 未实现 propagation.ValuesGetter,Baggage.Extract 只留下第一个成员,代理和服务网格常见的多成员请求都会丢数据,已修复;AddStaticFiles 在 os.Getwd() 失败时会静默回退到根目录,现在会记日志并提前返回。性能方面,span 名称与属性按 (method, route) 缓存复用,非录制场景分配从 21 次降到 11 次,行为不变。基础镜像升至 Go 1.27。
v1.60.02026-08-31
Release v1.60.0
🚀 Features
🔹 Opt-In Trie Router
GOFR_ROUTER=trie replaces mux's linear route scan with a radix trie, handing the final match decision back to Route.Match. mux stays the registry, so mux.Vars, route templates and registration are unchanged.
| routes | mux | trie | speedup |
|-------:|--------:|--------:|--------:|
| 10 | 506 ns | 461 ns | 1.1x |
| 50 | 1007 ns | 550 ns | 1.8x |
| 100 | 1642 ns | 548 ns | 3.0x |
| 200 | 2918 ns | 515 ns | 5.7x |
Gains start around 5-10 routes and cost 2 extra allocations per request. Routes the trie cannot safely index, and every non-match, fall back to mux, so an indexing mistake costs latency rather than 404ing a live route. Default behavior is unchanged.
🔹 Text Embeddings for LLMs
GoFr's ai package now supports text embeddings. Embed is a method on the LLM, alongside Chat and Stream, with the same tracing and token metrics. Vectors are placed by the provider's reported index rather than by response position, so a backend answering out of order cannot pair an input with the wrong vector.
``go
// embeddings are usually a different model from your chat one
app.AddLLM(&llm.Client{Provider: llm.OpenAI, Model: "text-embedding-3-small"}, gofr.WithName("embed"))
// in a handler
resp, err := ctx.LLM("embed").Embed(ctx, []string{"the quick brown fox"})
// resp.Embeddings[i] holds the vector for input[i]
`
A chat-only model reports ai.ErrEmbedNotSupported and an unregistered one ai.ErrLLMNotConfigured, so a misconfiguration surfaces as an ordinary error rather than a panic.
🔹 LLM Concurrency Limiting
llm.Client.MaxConcurrentRequests caps in-flight provider requests, for local models or tight rate-limit tiers where concurrent handler calls queue up and inflate tail latency. Excess Chat, Embed and Stream calls block until a slot frees, honoring their context deadline. Health probes are now single-flight. The default of 0 is unlimited.
🔧 Enhancements
🔹 Reduced Per-Request Allocations
The request hot path now uses 8 fewer allocations and 225 fewer bytes per request (49 → 41 allocs, 3915 → 3690 B), measured through a real GoFr handler. Four changes, none of which alters output:
- Lazy Context Logger: the 32-character trace ID was formatted, a one-entry marker map allocated and the wrapper heap-allocated at construction — before knowing whether the handler would log at all. The trace ID is now formatted at log time, the marker is a typed string rather than a map, and the wrapper is returned by value. A request that logs nothing costs 0 B and 0 allocs, down from 432 B and 5.
- Gated Request Logs: handleRequestLog built the entry, formatted a timestamp and resolved the client IP before the logger decided whether to emit it. An optional LogEnabled() lets the middleware ask first, saving 193 B and 4 allocs per request at LOG_LEVEL=NOTICE and above. The default INFO is unaffected, since the request log is written at INFO.
- Co-Allocated Request Objects: Context, Request and Responder are created together and discarded together, so they now live in one struct instead of three separate heap objects.
- Trace ID off the Hot Path: handler.ServeHTTP resolved a 32-character trace ID on every request for a consumer that only runs when a handler returns an error. It is built on the error path now.
Alongside those, remoteLogger.LogEnabled no longer takes a per-request RWMutex.RLock on a field it never read, and the log level moved to an atomic.Int64 — clearing 3 data races in pkg/gofr/logging/remotelogger under -race.
The first change moves work from per-request to per-log-call, so it breaks even at 3 discarded log lines per request. Output is byte-identical to v1.59.0: 348 request cases and every log line at all 7 levels were differenced with no changes.
🛠️ Fixes
- CORS Origin Bypass — A differently-cased access-control-allow-origin key slipped past both the header guard and parseOrigins, so a configured allow-list could answer an untrusted origin with *. Header names are now canonicalized at construction.
- CORS Data Race — append(routes, "OPTIONS") wrote into the backing array of the router's RegisteredRoutes. Reported 3 data races under -race, now clean.
- Content-Type Matching — Matching was case-sensitive and untrimmed, so Application/JSON and application/json ; charset=utf-8 bound nothing. Now parsed per RFC 9110, with application/octet-stream accepted alongside binary/octet-stream.
- Bind Silently Discarded Bodies — Bind into a non-pointer, and application/octet-stream into a target that is not []byte, unmarshalled into a throwaway and returned nil, so the handler saw success and no data. Both are reported now, which means a handler that returns the error responds 500 where it previously returned 201 with an empty struct. GoFr's own binary/octet-stream spelling already errored this way; the RFC spelling and the case variants now match their siblings.
- Bind Nil Body Panic — A request built by hand, as in a handler unit test, panicked in io.ReadAll. An absent body is now treated as empty.
- Dropped Response Headers — Headers set on a *response.Response never reached the wire.
- gRPC Shutdown Race — grpcServer.server was written and read across goroutines unsynchronized, and a Shutdown reading a stale nil reported success without stopping anything, letting the process exit with the server still serving.
- Cron Data Loss on Shutdown — Stop() returned as soon as the ticker halted without joining running jobs, so a job mid-work carried on against datasources App.Shutdown was already closing and failed with sql: database is closed, losing the rest of a half-written batch. Stop() now joins in-flight jobs, so it blocks for as long as the job runs; App.Shutdown caps that at its own context deadline. A container with no logger also segfaulted in job.run.
- Flaky Example Tests — All 31 time.Sleep calls replaced with real readiness signals, and using-migrations now owns its own MySQL and Redis databases.
📦 CI & Dependencies
- Dependency Updates — 26 Dependabot PRs consolidated: OpenTelemetry 1.45, prometheus exporter 0.67, go-redis 9.22.0 (with MockRedis regenerated), plus aws-sdk-go-v2, clickhouse-go, cloudsqlconn, x/crypto and sqlite. Note that the prometheus exporter now formats label values via attribute.Value.String(), so a StringSlice renders as [a,b] rather than ["a","b"].
- CI Hardening — Concurrency groups and job timeouts, actions pinned by commit SHA, service health checks in Example-Unit-Testing, and Node 24 in the website workflows. Dependabot now covers pkg/gofr/metrics/exporters/gcp and all 11 Dockerfiles, one of which had been left on alpine:3.14`.
---
Full changelog: https://github.com/gofr-dev/gofr/compare/v1.59.0...v1.60.0
v1.59.02026-08-13
v1.59.0:指标导出新增 OTLP 推送,与原有 Prometheus 拉取并行,面向 Cloud Run 缩容到零、短命任务这类抓取窗口根本碰不到进程的场景;两者是独立开关,不改配置则输出与之前逐字节一致,启用需设 METRICS_EXPORTER=otlp。修复三处:S3 文件存储的 Read 恒返回 len(p),导致 io.Copy 永不结束、缓冲区无限膨胀直至 OOM;静态端点根路径请求返回 403 或陷入重定向循环;服务关闭时的数据竞争。安全方面,/.well-known/health 原先向未认证调用者暴露数据库名、连接池统计等后端清单,现只返回 {name, status};examples/using-s3-filestore 的 grpc 升至 v1.83.0。性能上请求热路径减少分配,典型请求省下约 577 B 和 6 次分配。
v1.58.02026-07-21
Release v1.58.0
🚀 Features
🔹 LLM Support with Built-in Observability
Call LLMs directly from a handler, with tracing, token-usage metrics, logs and health wired
automatically — the same zero-config observability GoFr gives every datasource. Token usage
is captured per request and recorded as the appllmtokensperrequest histogram, labelled
by provider, model, status and token_type (prompt / completion / cached⊆prompt /
reasoning⊆completion), so cost and consumption are visible out of the box. Register a model with
app.AddLLM, then reach it via ctx.LLM(). Register additional named models and select one
per call. An OpenAI-compatible model can also wire from the environment with no code — set
LLMPROVIDER, LLMMODEL, LLMAPIKEY and skip AddLLM entirely. Providers:
OpenAI / Groq / DeepSeek / Together / Ollama, or any OpenAI-compatible BaseURL.
``go
app.AddLLM(&llm.Client{Provider: llm.Groq, Model: "llama-3.3-70b-versatile"})
resp, _ := ctx.LLM().Generate(ctx, prompt) // tracing + metrics automatic
// Register additional named models and select one per call.
app.AddLLM(&llm.Client{Provider: llm.OpenAI, Model: "gpt-4o-mini"}, gofr.WithName("fast"))
quick, _ := ctx.LLM("fast").Generate(ctx, prompt)
`
🔹 Server-Sent Events (SSE) Streaming
A new generic response.Stream special-response type streams values to the client over SSE
(and NDJSON) — useful for LLM token streaming, progress updates, or log tailing. Values are
pulled on demand over an unbuffered channel for backpressure, and the responder flushes via
http.NewResponseController. Streaming is transport, not tied to AI.
`go
func handler(ctx *gofr.Context) (any, error) {
return response.Stream{Source: tokens}, nil // flushed to the client as they arrive
}
`
🔹 MCP — Expose Your Service to AI Agents
app.EnableMCP() exposes your read-only handlers to AI agents as MCP tools. Tool calls are
rebuilt into *http.Requests and dispatched back through the real router, so Bind /
validation / RBAC / auth middleware all run and the caller's auth headers propagate
(ctx.GetAuthInfo() works). The same tools back ctx.LLM().Tools(), so you can build an
agent loop over your own service's endpoints.
`go
app.EnableMCP() // read-only handlers become MCP tools
tools := ctx.LLM().Tools() // build an agent loop over your own endpoints
`
🔹 S3 Signed URL Support
The S3 file store now implements GenerateSignedURL, making it a first-class
CloudFileSystem alongside GCS. URLs are signed locally with AWS Signature V4 (offline, no
new dependency), and an extensible flavor system lets the same store target S3-compatible
providers. Previously S3 returned ErrSignedURLsNotSupported.
🛠️ Fixes
- Subscriber Backoff on Handler Error — a failing pub/sub handler now propagates its
error to startSubscriber`, engaging the existing 2s backoff instead of tight-looping on
every consecutive failure. The recovered-panic sentinel still returns nil to avoid
duplicate logging.
- Dependency Updates — Consolidated minor/patch dependency updates and bumped GitHub
Actions to their latest major versions.
Full Changelog: https://github.com/gofr-dev/gofr/compare/v1.57.0...v1.58.0
v1.57.02026-06-24
Release v1.57.0
🚀 Features
🔹 Cloud SQL Datasource (GCP IAM Auth)
A new Postgres/MySQL Cloud SQL datasource that authenticates with GCP IAM database authentication on GCP and falls back to username/password locally — selected by DBIAMAUTH, with no code change. It ships in its own module so core gains no GCP dependencies, and adds a pluggable AddSQLDB so other providers can be wired in the same way.
``go
app := gofr.New()
app.AddSQLDB(cloudsql.New(app.Config)) // same line works locally and on GCP
app.Run()
`
🔹 File-Based Token Authentication for HTTP Services
HTTP services can now authenticate using a bearer token read from disk and refreshed on an interval, built for Kubernetes projected service account tokens. Configure via service.NewFileTokenAuthConfig(); it fails fast on a missing token and keeps serving the cached one if a refresh fails.
🔧 Enhancements
🔹 ClickHouse Connection-Pool Configuration
clickhouse.Config now accepts pool and dial settings (MaxOpenConns, MaxIdleConns, DialTimeout, ConnMaxLifetime). Earlier, apps were stuck on the driver's default pool, so high-concurrency services could hit acquire conn timeout with no way to raise the limit. Backward-compatible — unset fields keep the driver defaults.
`go
app.AddClickhouse(clickhouse.New(clickhouse.Config{
Hosts: app.Config.Get("HOSTS"),
Database: app.Config.Get("DATABASE"),
MaxOpenConns: 20, // optional pool tuning; omit for driver defaults
}))
`
🔹 Datasource Latency Histogram Buckets
Datasource latency histograms capped their buckets at 10, so for datasources that record in microseconds nearly every query fell into the +Inf` bucket and the histogram showed no usable distribution. Buckets now span 50µs–3 minutes in each datasource's native unit. Recorded values are unchanged; only the bucket boundaries widen.
🔹 gRPC Example Histogram Buckets
The gRPC examples capped buckets at 10ms, which pegged p95 latency at 10ms for normal RPCs. Buckets now scale up to 30s for accurate latency tracking.
Full Changelog: https://github.com/gofr-dev/gofr/compare/v1.56.7...v1.57.0
v1.56.72026-06-05
Release v1.56.7
⚡ Performance — HTTP Hot Path
Reduced per-request allocations and CPU across the pkg/gofr request lifecycle, closing most of the gap to the net/http router cluster.
Benchmark setup: Apple M4, GOMAXPROCS=4, payloads: plaintext (13 B), json (small object), param (single path param). Numbers are machine-specific and will differ on Linux/x86, in containers with CPU limits, and at higher core counts — treat as relative, not absolute.
End-to-end RPS (vs v1.56.6):
| Endpoint | v1.56.6 | v1.56.7 | Δ |
|-----------|--------:|---------:|-------:|
| plaintext | 89,835 | 133,304 | +48 % |
| json | 89,177 | 118,513 | +33 % |
| param | 87,224 | 121,159 | +39 % |
Per-request profile (pprof):
| Metric | v1.56.6 | v1.56.7 | Δ |
|-------------------------|--------:|--------:|------:|
| Allocations / req | 132 KB | 60 KB | −54 % |
| CPU / req | 33.5 µs | 21 µs | −37 % |
| p99 latency (plaintext) | 3.7 ms | 1.7 ms | −54 % |
What changed
| Area | Change | Impact |
|------|--------|--------|
| OTel hot path | When TRACEEXPORTER is unset, installs a NeverSample() TracerProvider; otel.Tracer(...) handle cached in the middleware closure | Spans keep unique TraceID/SpanID for log correlation but short-circuit at the sampler — 528 B → 144 B / req** |
| Middleware | StatusResponseWriter shared between Logging and Metrics and pooled; attribute slices cached per (route, method); time.Now() deferred past probe/GraphQL filters | Fewer allocations per request |
| Response & routing | Single Write with a Content-Length header (was 2–3 Writes); path.Clean skipped on already-canonical URLs; handler runs inline (no goroutine) when there's no request timeout and the request isn't a WebSocket upgrade | Lower CPU and allocations on the response path |
🛠️ Fixes
🔹 Tracing spans
HTTP semconv attributes (http.method, http.route, http.status_code) are now recorded natively on the request span, and the redundant per-route otelhttp.NewHandler wrap has been removed.
- Eliminates the duplicate span emitted per request (2 spans/req → 1).
- Span name corrected from the generic gofr-router to the standard <METHOD> <route-template> (e.g. GET /users/{id}), matching OTel HTTP semantic conventions.
> Note on tracing defaults: the NeverSample() provider only applies when TRACEEXPORTER is unset — i.e. when tracing isn't configured at all. If you set TRACEEXPORTER, sampling and export behave as before. No configured setup is affected.
Full Changelog: https://github.com/gofr-dev/gofr/compare/v1.56.6...v1.56.7