-
Notifications
You must be signed in to change notification settings - Fork 1
Expand file tree
/
Copy pathcontext.go
More file actions
834 lines (735 loc) · 26 KB
/
context.go
File metadata and controls
834 lines (735 loc) · 26 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
// Copyright 2025 The Rivaas Authors
//
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
package app
import (
"bytes"
"context"
"errors"
"fmt"
"io"
"log/slog"
"net/http"
"reflect"
"strings"
"go.opentelemetry.io/otel/attribute"
"go.opentelemetry.io/otel/trace"
"rivaas.dev/binding"
"rivaas.dev/router"
"rivaas.dev/tracing"
"rivaas.dev/validation"
riverrors "rivaas.dev/errors"
)
// defaultFormatter is the package-level default RFC9457 formatter used when app
// has no error config or when content negotiation has no match. Pre-allocated
// to avoid allocating on every error response.
var defaultFormatter = riverrors.MustNew()
// Context wraps router.Context with app-level features including binding and validation.
// Context embeds router.Context to provide all HTTP routing functionality while adding
// high-level integration with binding and validation packages.
//
// Context instances are pooled by the App and reused across requests. They are normally
// created and initialized by the App (via the pool and wrapHandler). When constructing
// a Context for tests (e.g. from the pool), set app for app-specific error formatter,
// logging, and observability. If app is nil, methods like Fail() still work using the
// default error formatter and slog.Default().
//
// The app field is an intentional back-reference to the App instance. It enables
// convenience methods (Fail, StartSpan, FinishSpan, RecordHistogram, IncrementCounter,
// Tracer, etc.) to access app-level services without requiring every handler to accept
// extra parameters. The reference is set once per pool cycle in wrapHandler and does
// not cause per-request allocation.
type Context struct {
*router.Context // Embed router context for HTTP functionality
app *App // Back reference to app for app-level services (intentional; see type doc)
// Binding metadata (per-request)
bindingMeta *bindingMetadata
}
// bindingMetadata holds a per-request binding state.
// bindingMetadata caches request body and tracks field presence for validation.
type bindingMetadata struct {
bodyRead bool // Whether the body has been read
rawBody []byte // Cached raw body bytes
presence validation.PresenceMap // Tracks which fields are present in the request
}
// Bind binds request data and validates it.
// Bind is the recommended method for handling request input.
//
// Bind automatically:
// - Detects Content-Type and binds from appropriate sources
// - Binds path, query, header, and cookie parameters based on struct tags
// - Validates the bound struct using the configured strategy
// - Tracks field presence for partial validation support
//
// Supported sources based on tags:
// - path: "name" - URL path parameters
// - query: "name" - Query string parameters
// - header: "name" - HTTP headers
// - cookie: "name" - Cookies
// - json: "name" - JSON request body
// - form: "name" - Form data (application/x-www-form-urlencoded or multipart/form-data)
//
// For binding without validation, use [Context.BindOnly].
// For separate binding and validation, use [Context.BindOnly] and [Context.Validate].
//
// Errors:
// - [binding.ErrOutMustBePointer]: out is not a pointer to struct or map
// - [binding.ErrRequestBodyNil]: request body is nil when JSON/form binding is needed
// - [binding.ErrUnsupportedContentType]: Content-Type is not supported
// - [validation.Error]: validation failed (one or more field errors)
//
// Example:
//
// var req CreateUserRequest
// if err := c.Bind(&req); err != nil {
// c.Fail(err)
// return
// }
//
// With options:
//
// if err := c.Bind(&req, app.WithStrict(), app.WithPartial()); err != nil {
// c.Fail(err)
// return
// }
//
// Note: For multipart forms with file uploads, files must be retrieved
// separately using c.File() or c.Files().
func (c *Context) Bind(out any, opts ...BindOption) error {
cfg, err := applyBindOptions(opts)
if err != nil {
return err
}
// Step 1: Binding
if err = c.bindInternal(out, cfg); err != nil {
return err
}
// Step 2: Validation (unless skipped)
if !cfg.skipValidation {
if err = c.validateInternal(out, cfg); err != nil {
return err
}
}
return nil
}
// bindInternal performs the binding step with the given configuration.
func (c *Context) bindInternal(out any, cfg *bindConfig) error {
// Build binding options
bindOpts := cfg.bindingOpts
if cfg.strict {
bindOpts = append(bindOpts, binding.WithUnknownFields(binding.UnknownError))
}
// Get struct type for introspection
t := reflect.TypeOf(out)
if t.Kind() != reflect.Pointer {
return binding.ErrOutMustBePointer
}
if t.Elem().Kind() != reflect.Struct && t.Elem().Kind() != reflect.Map {
return binding.ErrOutMustBePointer
}
elemType := t.Elem()
isMap := elemType.Kind() == reflect.Map
// For structs, bind from non-body sources (params, query, header, cookie)
if !isMap {
if err := binding.BindTo(out,
binding.FromPath(c.AllParams()),
binding.FromQuery(c.Request.URL.Query()),
binding.FromHeader(c.Request.Header),
binding.FromCookie(c.Request.Cookies()),
); err != nil {
return err
}
}
// Handle body binding
// For maps, always try to bind body (maps don't have struct tags)
// For structs, check if they have json/form tags
if isMap || hasJSONOrFormTag(elemType) {
contentType := c.Request.Header.Get("Content-Type")
// Extract base content type (remove parameters)
if idx := strings.Index(contentType, ";"); idx != -1 {
contentType = contentType[:idx]
}
contentType = strings.TrimSpace(strings.ToLower(contentType))
switch contentType {
case "application/json", "application/merge-patch+json", "application/json-patch+json", "":
// Default to JSON if no content type specified
return c.bindJSON(out, bindOpts)
case "application/x-www-form-urlencoded":
return c.bindForm(out)
case "multipart/form-data":
return c.bindForm(out)
default:
// For maps, default to JSON even if the content-type is missing
if isMap {
return c.bindJSON(out, bindOpts)
}
return fmt.Errorf("%w: %s", binding.ErrUnsupportedContentType, contentType)
}
}
return nil
}
// validateInternal performs the validation step with the given configuration.
func (c *Context) validateInternal(out any, cfg *bindConfig) error {
ctx := c.Request.Context()
// Inject raw JSON if available
if c.bindingMeta != nil && len(c.bindingMeta.rawBody) > 0 {
ctx = validation.InjectRawJSONCtx(ctx, c.bindingMeta.rawBody)
}
// Build validation options
valOpts := []validation.Option{
validation.WithContext(ctx),
}
// Handle partial validation
if cfg.partial {
valOpts = append(valOpts, validation.WithPartial(true))
}
// Inject presence map
pm := cfg.presence
if pm == nil {
pm = c.Presence()
}
if pm != nil {
valOpts = append(valOpts, validation.WithPresence(pm))
}
// Handle strict mode for validation
if cfg.strict {
valOpts = append(valOpts, validation.WithDisallowUnknownFields(true))
}
// Append user-provided validation options
valOpts = append(valOpts, cfg.validationOpts...)
if c.app != nil && c.app.validationEngine != nil {
return c.app.validationEngine.Validate(ctx, out, valOpts...)
}
return validation.Validate(ctx, out, valOpts...)
}
// hasJSONOrFormTag checks if the struct has any "json" or form tags.
func hasJSONOrFormTag(t reflect.Type) bool {
return binding.HasStructTag(t, binding.TagJSON) || binding.HasStructTag(t, binding.TagForm)
}
// bindJSON binds JSON request body to a struct.
func (c *Context) bindJSON(out any, opts []binding.Option) error {
req := c.Request
if req.Body == nil {
return binding.ErrRequestBodyNil
}
// Read and cache body
if c.bindingMeta == nil {
c.bindingMeta = &bindingMetadata{}
}
if !c.bindingMeta.bodyRead {
body, err := io.ReadAll(req.Body)
if err != nil {
return fmt.Errorf("failed to read body: %w", err)
}
c.bindingMeta.rawBody = body
c.bindingMeta.bodyRead = true
// Refill for downstream middleware
c.Request.Body = io.NopCloser(bytes.NewReader(body))
// Track presence using validation package
if pm, presenceErr := validation.ComputePresence(body); presenceErr == nil {
c.bindingMeta.presence = pm
}
// Store raw JSON in context for schema validation
c.Request = c.Request.WithContext(
validation.InjectRawJSONCtx(c.Request.Context(), body),
)
}
// Translate binding.UnknownFieldError to validation.Error for consistency
err := binding.JSONTo(c.bindingMeta.rawBody, out, opts...)
var unkErr *binding.UnknownFieldError
if errors.As(err, &unkErr) {
return &validation.Error{
Fields: []validation.FieldError{{
Code: "json.unknown_field",
Message: unkErr.Error(),
}},
}
}
return err
}
// MustBind binds and validates, writing an error response on failure.
// Returns true if successful, false if an error was written.
//
// MustBind eliminates boilerplate error handling for the common case.
//
// Example:
//
// var req CreateUserRequest
// if !c.MustBind(&req) {
// return // Error already written
// }
// // Continue with validated request
func (c *Context) MustBind(out any, opts ...BindOption) bool {
if err := c.Bind(out, opts...); err != nil {
c.Fail(err)
return false
}
return true
}
// BindOnly binds request data without validation.
// Use when you need fine-grained control over the bind/validate lifecycle.
//
// Example:
//
// var req Request
// if err := c.BindOnly(&req); err != nil {
// c.Fail(err)
// return
// }
// req.Normalize() // Custom processing
// if err := c.Validate(&req); err != nil {
// c.Fail(err)
// return
// }
func (c *Context) BindOnly(out any, opts ...BindOption) error {
cfg, err := applyBindOptions(opts)
if err != nil {
return err
}
return c.bindInternal(out, cfg)
}
// Validate validates a struct using the configured validation strategy.
// Use after [BindOnly] for fine-grained control.
// Options are app-scoped: use [WithValidatePartial], [WithValidateStrict], or [WithValidateOptions].
//
// Example:
//
// if err := c.Validate(&req, app.WithValidatePartial()); err != nil {
// c.Fail(err)
// return
// }
func (c *Context) Validate(v any, opts ...ValidateOption) error {
ctx := c.Request.Context()
// Inject raw JSON if available
if c.bindingMeta != nil && len(c.bindingMeta.rawBody) > 0 {
ctx = validation.InjectRawJSONCtx(ctx, c.bindingMeta.rawBody)
}
cfg, err := applyValidateOptions(opts)
if err != nil {
return err
}
allOpts := []validation.Option{
validation.WithContext(ctx),
}
if pm := c.Presence(); pm != nil {
allOpts = append(allOpts, validation.WithPresence(pm))
}
if cfg.partial {
allOpts = append(allOpts, validation.WithPartial(true))
}
if cfg.strict {
allOpts = append(allOpts, validation.WithDisallowUnknownFields(true))
}
allOpts = append(allOpts, cfg.validationOpts...)
if c.app != nil && c.app.validationEngine != nil {
return c.app.validationEngine.Validate(ctx, v, allOpts...)
}
return validation.Validate(ctx, v, allOpts...)
}
// Presence returns the presence map for the current request.
// Presence returns nil if no binding has occurred yet.
//
// Example:
//
// pm := c.Presence()
// if pm != nil && pm.Has("email") {
// // email field was present in request
// }
func (c *Context) Presence() validation.PresenceMap {
if c.bindingMeta == nil {
return nil
}
return c.bindingMeta.presence
}
// ResetBinding resets the binding metadata for this context.
// ResetBinding is useful for testing or when you need to rebind a request.
func (c *Context) ResetBinding() {
c.bindingMeta = nil
}
// bindForm binds form data to a struct.
func (c *Context) bindForm(out any) error {
req := c.Request
contentType := req.Header.Get("Content-Type")
// Parse the appropriate form type
if strings.HasPrefix(contentType, "multipart/form-data") {
if err := req.ParseMultipartForm(32 << 20); err != nil { // 32 MB max
return fmt.Errorf("failed to parse multipart form: %w", err)
}
return binding.MultipartTo(req.MultipartForm, out)
}
if err := req.ParseForm(); err != nil {
return fmt.Errorf("failed to parse form: %w", err)
}
return binding.FormTo(req.Form, out)
}
// Fail responds with a formatted error using the configured formatter.
// Fail automatically aborts the handler chain after writing the response.
//
// Fail is the recommended way to return errors in handlers.
// The HTTP status is determined from the error (via ErrorType interface)
// or defaults to 500 Internal Server Error.
//
// Fail selects the formatter based on:
// - Content negotiation (Accept header) if multiple formatters are configured
// - Default formatter if single formatter is configured
// - RFC 9457 formatter as ultimate fallback
//
// Example:
//
// if err := c.Bind(&req); err != nil {
// c.Fail(err)
// return
// }
//
// if user == nil {
// c.Fail(fmt.Errorf("user not found"))
// return
// }
//
// See also [Context.FailStatus] for explicit status codes and convenience methods
// like [Context.NotFound], [Context.BadRequest], [Context.Unauthorized].
//
// To collect multiple errors and respond later (e.g. multi-field validation), use
// c.Context.CollectError(err), then c.Context.HasErrors() / c.Context.Errors() and send one response.
func (c *Context) Fail(err error) {
if err == nil {
return
}
c.fail(err)
}
// FailStatus responds with an error and explicit status code.
// FailStatus automatically aborts the handler chain.
//
// FailStatus is useful when you want to override the error's default status.
//
// Example:
//
// c.FailStatus(http.StatusNotFound, err)
// c.FailStatus(http.StatusBadRequest, validationErr)
func (c *Context) FailStatus(status int, err error) {
c.fail(riverrors.WithStatus(err, status))
}
// fail is the internal implementation that formats and writes the error response.
func (c *Context) fail(err error) {
// Abort handler chain to prevent further processing
c.Abort()
logger := slog.Default()
if c.app != nil {
logger = c.app.BaseLogger()
}
// Select a formatter based on configuration
formatter := c.selectFormatter()
// Format the error (formatter is framework-agnostic)
response := formatter.Format(c.Request, err)
// Log error with request context (trace_id/span_id injected automatically by contextHandler)
logger.ErrorContext(c.RequestContext(), "handler error",
"error", err,
"method", c.Request.Method,
"path", c.Request.URL.Path,
"status", response.Status,
)
// Write response
c.Header("Content-Type", response.ContentType)
if response.Headers != nil {
for key, values := range response.Headers {
for _, value := range values {
c.Header(key, value)
}
}
}
if jsonErr := c.JSON(response.Status, response.Body); jsonErr != nil {
logger.ErrorContext(c.RequestContext(), "failed to write JSON response", "err", jsonErr)
}
}
// selectFormatter chooses the appropriate formatter based on configuration.
// selectFormatter is a private helper used by Fail().
func (c *Context) selectFormatter() riverrors.Formatter {
if c.app == nil {
return defaultFormatter
}
cfg := c.app.config.errors
if cfg == nil {
// Fallback to default
return defaultFormatter
}
// Single formatter mode
if cfg.formatter != nil {
return cfg.formatter
}
// Multi-formatter mode with content negotiation
if len(cfg.formatters) > 0 {
// Build list of acceptable media types
offers := make([]string, 0, len(cfg.formatters))
for mediaType := range cfg.formatters {
offers = append(offers, mediaType)
}
// Use router's content negotiation
match := c.Accepts(offers...)
if match != "" {
if formatter, ok := cfg.formatters[match]; ok {
return formatter
}
}
// Fallback to default format
if cfg.defaultFormat != "" {
if formatter, ok := cfg.formatters[cfg.defaultFormat]; ok {
return formatter
}
}
// Predictable fallback - always use RFC9457
return defaultFormatter
}
// Ultimate fallback
return defaultFormatter
}
// NotFound responds with a 404 Not Found error.
// Pass nil for a generic "Not Found" message.
//
// Example:
//
// c.NotFound(nil) // generic "Not Found"
// c.NotFound(fmt.Errorf("user %s not found", id)) // custom message
// c.NotFound(ErrUserNotFound) // domain error
func (c *Context) NotFound(err error) {
c.FailStatus(http.StatusNotFound, err)
}
// BadRequest responds with a 400 Bad Request error.
// Pass nil for a generic "Bad Request" message.
//
// Example:
//
// c.BadRequest(nil) // generic
// c.BadRequest(validationErr) // with validation details
func (c *Context) BadRequest(err error) {
c.FailStatus(http.StatusBadRequest, err)
}
// Unauthorized responds with a 401 Unauthorized error.
// Pass nil for a generic "Unauthorized" message.
//
// Example:
//
// c.Unauthorized(nil) // generic
// c.Unauthorized(fmt.Errorf("invalid token")) // custom message
func (c *Context) Unauthorized(err error) {
c.FailStatus(http.StatusUnauthorized, err)
}
// Forbidden responds with a 403 Forbidden error.
// Pass nil for a generic "Forbidden" message.
//
// Example:
//
// c.Forbidden(nil) // generic
// c.Forbidden(fmt.Errorf("insufficient permissions")) // custom message
func (c *Context) Forbidden(err error) {
c.FailStatus(http.StatusForbidden, err)
}
// Conflict responds with a 409 Conflict error.
// Pass nil for a generic "Conflict" message.
//
// Example:
//
// c.Conflict(nil) // generic
// c.Conflict(fmt.Errorf("user already exists")) // custom message
func (c *Context) Conflict(err error) {
c.FailStatus(http.StatusConflict, err)
}
// Gone responds with a 410 Gone error.
// Pass nil for a generic "Gone" message.
//
// Example:
//
// c.Gone(nil) // generic
// c.Gone(fmt.Errorf("resource permanently deleted")) // custom message
func (c *Context) Gone(err error) {
c.FailStatus(http.StatusGone, err)
}
// UnprocessableEntity responds with a 422 Unprocessable Entity error.
// Pass nil for a generic "Unprocessable Entity" message.
//
// Example:
//
// c.UnprocessableEntity(nil) // generic
// c.UnprocessableEntity(validationErr) // validation details
func (c *Context) UnprocessableEntity(err error) {
c.FailStatus(http.StatusUnprocessableEntity, err)
}
// TooManyRequests responds with a 429 Too Many Requests error.
// Pass nil for a generic "Too Many Requests" message.
//
// Example:
//
// c.TooManyRequests(nil) // generic
// c.TooManyRequests(fmt.Errorf("rate limit exceeded")) // custom message
func (c *Context) TooManyRequests(err error) {
c.FailStatus(http.StatusTooManyRequests, err)
}
// InternalError responds with a 500 Internal Server Error.
// Pass nil for a generic "Internal Server Error" message.
//
// Example:
//
// c.InternalError(nil) // generic
// c.InternalError(err) // with error details (logged but sanitized in response)
func (c *Context) InternalError(err error) {
c.FailStatus(http.StatusInternalServerError, err)
}
// ServiceUnavailable responds with a 503 Service Unavailable error.
// Pass nil for a generic "Service Unavailable" message.
//
// Example:
//
// c.ServiceUnavailable(nil) // generic
// c.ServiceUnavailable(fmt.Errorf("maintenance mode")) // custom message
func (c *Context) ServiceUnavailable(err error) {
c.FailStatus(http.StatusServiceUnavailable, err)
}
// Observability methods — delegate to app's metrics and tracing.
// These methods are no-ops when observability is not configured.
// TraceID returns the current trace ID from the active span.
// Returns an empty string if tracing is not active.
func (c *Context) TraceID() string {
return tracing.TraceID(c.RequestContext())
}
// SpanID returns the current span ID from the active span.
// Returns an empty string if tracing is not active.
func (c *Context) SpanID() string {
return tracing.SpanID(c.RequestContext())
}
// SetSpanAttribute adds an attribute to the current span.
// This is a no-op if tracing is not active.
func (c *Context) SetSpanAttribute(key string, value any) {
tracing.SetSpanAttributeFromContext(c.RequestContext(), key, value)
}
// AddSpanEvent adds an event to the current span with optional attributes.
// This is a no-op if tracing is not active.
func (c *Context) AddSpanEvent(name string, attrs ...attribute.KeyValue) {
tracing.AddSpanEventFromContext(c.RequestContext(), name, attrs...)
}
// TraceContext returns the request context (which carries the active span when tracing is enabled).
// Use it for manual span creation or context propagation.
func (c *Context) TraceContext() context.Context {
return c.RequestContext()
}
// Span returns the OpenTelemetry span for this request, if tracing is enabled.
// Returns a non-recording span if tracing is not enabled.
func (c *Context) Span() trace.Span {
return trace.SpanFromContext(c.RequestContext())
}
// Tracer returns the app's tracer, or nil if tracing is not configured.
// Use Tracer() only when you need to pass the tracer to another library (e.g. DB driver,
// HTTP client) or use tracer-specific options (inject/extract). For child spans in handlers,
// use StartSpan and FinishSpan instead.
func (c *Context) Tracer() *tracing.Tracer {
if c.app == nil {
return nil
}
return c.app.tracing
}
// StartSpan starts a child span with the given name. It is the single, discoverable way
// to create child spans from handlers. Always end the span with FinishSpan or
// FinishSpanWithHTTPStatus (e.g. defer c.FinishSpan(span)).
// If tracing is nil or disabled, returns the request context and a non-recording span.
func (c *Context) StartSpan(name string, opts ...trace.SpanStartOption) (context.Context, trace.Span) {
if c.app == nil || c.app.tracing == nil || !c.app.tracing.IsEnabled() {
return c.RequestContext(), trace.SpanFromContext(c.RequestContext())
}
return c.app.tracing.StartSpan(c.RequestContext(), name, opts...)
}
// FinishSpan ends a child span with status Ok. Use for spans that complete successfully
// and have no HTTP status. Delegates to tracing.FinishSpan. No-op if app/tracing nil.
func (c *Context) FinishSpan(span trace.Span) {
if c.app == nil || c.app.tracing == nil {
return
}
c.app.tracing.FinishSpan(span)
}
// FinishSpanWithHTTPStatus ends a child span and sets status from the HTTP status code.
// Delegates to tracing.FinishSpanWithHTTPStatus. No-op if app/tracing nil.
func (c *Context) FinishSpanWithHTTPStatus(span trace.Span, statusCode int) {
if c.app == nil || c.app.tracing == nil {
return
}
c.app.tracing.FinishSpanWithHTTPStatus(span, statusCode)
}
// FinishSpanWithError marks the span as failed with the given error and ends it.
// Delegates to tracing.FinishSpanWithError. No-op if app/tracing nil.
func (c *Context) FinishSpanWithError(span trace.Span, err error) {
if c.app == nil || c.app.tracing == nil {
return
}
c.app.tracing.FinishSpanWithError(span, err)
}
// RecordError records an error on the current request span without ending it.
// Delegates to tracing.RecordErrorFromContext(c.RequestContext(), err). No-op if app/tracing nil.
func (c *Context) RecordError(err error) {
if c.app == nil || c.app.tracing == nil {
return
}
tracing.RecordErrorFromContext(c.RequestContext(), err)
}
// CopyTraceContext returns a new context that carries the current trace for use in
// goroutines or background work. Delegates to tracing.CopyTraceContext(c.RequestContext()).
func (c *Context) CopyTraceContext() context.Context {
if c.app == nil || c.app.tracing == nil {
return context.Background()
}
return tracing.CopyTraceContext(c.RequestContext())
}
// WithSpan runs fn under a new span with the given name. The span is finished with
// success if fn returns nil, or with error if fn returns non-nil. Returns the error from fn.
// No-op if app/tracing nil (runs fn and returns its error). Delegates to StartSpan and
// FinishSpan/FinishSpanWithError.
func (c *Context) WithSpan(name string, fn func(context.Context) error) error {
if c.app == nil || c.app.tracing == nil || !c.app.tracing.IsEnabled() {
return fn(c.RequestContext())
}
ctx, span := c.StartSpan(name)
var err error
defer func() {
if err != nil {
c.FinishSpanWithError(span, err)
} else {
c.FinishSpan(span)
}
}()
err = fn(ctx)
return err
}
// RecordHistogram records a custom histogram metric.
// This is a no-op when metrics are not configured.
func (c *Context) RecordHistogram(name string, value float64, attributes ...attribute.KeyValue) {
if c.app != nil && c.app.metrics != nil {
_ = c.app.metrics.RecordHistogram(c.RequestContext(), name, value, attributes...) //nolint:errcheck // metrics failures must not break request handling
}
}
// IncrementCounter increments a custom counter metric by one.
// This is a no-op when metrics are not configured.
func (c *Context) IncrementCounter(name string, attributes ...attribute.KeyValue) {
if c.app != nil && c.app.metrics != nil {
_ = c.app.metrics.IncrementCounter(c.RequestContext(), name, attributes...) //nolint:errcheck // metrics failures must not break request handling
}
}
// AddCounter adds a value to a custom counter metric.
// This is a no-op when metrics are not configured.
func (c *Context) AddCounter(name string, value int64, attributes ...attribute.KeyValue) {
if c.app != nil && c.app.metrics != nil {
_ = c.app.metrics.AddCounter(c.RequestContext(), name, value, attributes...) //nolint:errcheck // metrics failures must not break request handling
}
}
// SetGauge sets a custom gauge metric.
// This is a no-op when metrics are not configured.
func (c *Context) SetGauge(name string, value float64, attributes ...attribute.KeyValue) {
if c.app != nil && c.app.metrics != nil {
_ = c.app.metrics.SetGauge(c.RequestContext(), name, value, attributes...) //nolint:errcheck // metrics failures must not break request handling
}
}