forked from jkaninda/okapi
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathcontext.go
More file actions
892 lines (787 loc) · 24.7 KB
/
Copy pathcontext.go
File metadata and controls
892 lines (787 loc) · 24.7 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
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
/*
* MIT License
*
* Copyright (c) 2025 Jonas Kaninda
*
* Permission is hereby granted, free of charge, to any person obtaining a copy
* of this software and associated documentation files (the "Software"), to deal
* in the Software without restriction, including without limitation the rights
* to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
* copies of the Software, and to permit persons to whom the Software is
* furnished to do so, subject to the following conditions:
*
* The above copyright notice and this permission notice shall be included in all
* copies or substantial portions of the Software.
*
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
* FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
* AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
* LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
* OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE
* SOFTWARE.
*/
package okapi
import (
"context"
"encoding/json"
"encoding/xml"
"fmt"
"html/template"
"log/slog"
"mime/multipart"
"net/http"
"net/url"
"path"
"reflect"
"strconv"
"strings"
"sync"
"time"
"github.com/gorilla/mux"
"gopkg.in/yaml.v3"
)
type (
Context struct {
okapi *Okapi
// request is the http.Request object
request *http.Request
// response http.ResponseWriter
response ResponseWriter
// store is a key/value store for storing data in the context
store *Store
errorHandler ErrorHandler
// handlers is the chain of middleware + final handler for the current request
handlers []HandlerFunc
// index tracks the current position in the handler chain
index int
}
Store struct {
mu sync.RWMutex
data map[string]any
}
// C is a shortcut of *Context
C = *Context
Ctx = *Context
)
// Mime types
const (
constJSON = "application/json"
constJSONProblem = "application/problem+json"
constXML = "application/xml"
constXMLProblem = "application/problem+xml"
constHTML = "text/html"
constFormData = "multipart/form-data"
constPLAINTEXT = "text/plain"
constYAML = "application/yaml"
constYamlX = "application/x-yaml"
constYamlText = "text/yaml"
constPROTOBUF = "application/protobuf"
)
// ************** Accessors *************
// newStoreData creates a new instance of Store
func newStoreData() *Store {
return &Store{
data: make(map[string]any),
}
}
func getAs[T any](c *Context, key string) (v T, ok bool) {
raw, exists := c.Get(key)
if !exists {
return
}
v, ok = raw.(T)
return
}
// Request a new Context instance with the given request
func (c *Context) Request() *http.Request {
return c.request // Return the request object
}
// Context returns the context.Context associated with the current request.
func (c *Context) Context() context.Context {
return c.request.Context()
}
// Response returns the http.ResponseWriter for writing responses.
// This is an alias for ResponseWriter for convenience.
func (c *Context) Response() ResponseWriter {
return c.response // Return the response writer
}
// ResponseWriter returns the http.ResponseWriter for writing responses.
func (c *Context) ResponseWriter() http.ResponseWriter {
return c.response // Return the http.ResponseWriter
}
// Logger returns the logger instance associated with the Okapi context.
func (c *Context) Logger() *slog.Logger {
if c.okapi.logger == nil {
return slog.Default()
}
return c.okapi.logger
}
// Next executes the next handler in the middleware chain.
// It should be called inside middleware to pass control to the next middleware or final handler.
func (c *Context) Next() error {
c.index++
if c.index < len(c.handlers) {
return c.handlers[c.index](c)
}
return nil
}
// Get retrieves a value from the context's data store with thread-safe access.
// Returns the value and a boolean indicating if the key exists.
func (c *Context) Get(key string) (any, bool) {
if c.store == nil {
return nil, false
}
c.store.mu.RLock()
defer c.store.mu.RUnlock()
val, ok := c.store.data[key]
return val, ok
}
// GetTime retrieves a time.Time value from the context's data store.
func (c *Context) GetTime(key string) (time.Time, bool) {
if val, ok := getAs[time.Time](c, key); ok {
return val, true
}
return time.Time{}, false
}
// Set stores a value in the context's data store with thread-safe access.
// Initializes the data map if it doesn't exist.
func (c *Context) Set(key string, value any) {
if c.store == nil {
c.store = newStoreData()
}
c.store.mu.Lock()
c.store.data[key] = value
c.store.mu.Unlock()
}
// GetString retrieves a string value from the context.
// Returns empty string if key doesn't exist or value isn't a string.
func (c *Context) GetString(key string) string {
if val, ok := getAs[string](c, key); ok {
return val
}
return ""
}
// GetBool retrieves a boolean value from the context.
// Returns false if key doesn't exist or value isn't a bool.
func (c *Context) GetBool(key string) bool {
if val, ok := getAs[bool](c, key); ok {
return val
}
// Try converting from string
if s, ok := getAs[string](c, key); ok {
return s == constTRUE
}
return false
}
// GetInt retrieves an integer value from the context.
// Returns 0 if key doesn't exist or value isn't an int.
func (c *Context) GetInt(key string) int {
if val, ok := getAs[int](c, key); ok {
return val
}
// Try converting from string (e.g. values set by JWT ForwardClaims)
if s, ok := getAs[string](c, key); ok {
if n, err := strconv.Atoi(s); err == nil {
return n
}
}
// Try converting from float64 (e.g. raw JSON-decoded numbers)
if f, ok := getAs[float64](c, key); ok {
return int(f)
}
return 0
}
// GetInt64 retrieves an int64 value from the context.
// Returns 0 if key doesn't exist or value isn't an int64.
func (c *Context) GetInt64(key string) int64 {
if val, ok := getAs[int64](c, key); ok {
return val
}
// Try converting from string
if s, ok := getAs[string](c, key); ok {
if n, err := strconv.ParseInt(s, 10, 64); err == nil {
return n
}
}
// Try converting from float64
if f, ok := getAs[float64](c, key); ok {
return int64(f)
}
return 0
}
// Copy creates a shallow copy of the context with a new data map.
func (c *Context) Copy() *Context {
newCtx := &Context{
request: c.request, // Copy request reference
response: c.response, // Copy response reference
store: newStoreData(), // Initialize new data map
handlers: c.handlers, // Share handler chain
index: c.index, // Copy current position
}
// Copy all key-value pairs to the new context
for k, v := range c.store.data {
newCtx.store.data[k] = v
}
return newCtx
}
// ************** request Utilities *****************
// RealIP returns the client's real IP address, handling proxies.
func (c *Context) RealIP() string {
return realIP(c.request)
}
// Referer retrieves the Referer header value from the request.
func (c *Context) Referer() string {
return c.request.Referer() // Get Referer header
}
// PathParam retrieves a URL path parameter value.
func (c *Context) PathParam(key string) string {
return mux.Vars(c.request)[key]
}
// Param is a short alias for PathParam.
func (c *Context) Param(key string) string {
return c.PathParam(key)
}
// Path returns the raw request path (e.g. "/users/123").
func (c *Context) Path() string {
return c.request.URL.Path
}
// Params returns all URL path parameters as a map.
func (c *Context) Params() map[string]string {
return mux.Vars(c.request)
}
// Query retrieves a URL query parameter value.
// Returns empty string if parameter doesn't exist.
func (c *Context) Query(key string) string {
return c.request.URL.Query().Get(key) // Get from URL query string
}
// QueryArray retrieves all values for a query parameter.
// Supports both repeated params (?tags=a&tags=b) and comma-separated (?tags=a,b).
func (c *Context) QueryArray(key string) []string {
values, ok := c.request.URL.Query()[key]
if !ok {
return nil
}
var result []string
for _, v := range values {
parts := strings.Split(v, ",")
for _, p := range parts {
if trimmed := strings.TrimSpace(p); trimmed != "" {
result = append(result, trimmed)
}
}
}
return result
}
// QueryMap returns all query parameters as a map.
// Only includes the first value for each parameter.
func (c *Context) QueryMap() map[string]string {
values := c.request.URL.Query()
result := make(map[string]string, len(values))
for k, v := range values {
if len(v) > 0 {
result[k] = v[0] // Take first value for each key
}
}
return result
}
// Accept returns the Accept header values as a slice.
func (c *Context) Accept() []string {
accept := c.request.Header.Get("Accept")
if accept == "" {
return nil // Return nil if header not present
}
return strings.Split(accept, ",") // Split by comma
}
// AcceptLanguage returns the Accept-Language header values as a slice.
// Trims whitespace from each language tag.
func (c *Context) AcceptLanguage() []string {
languages := c.request.Header.Get("Accept-Language")
if languages == "" {
return nil // Return nil if header not present
}
parts := strings.Split(languages, ",")
for i, lang := range parts {
parts[i] = strings.TrimSpace(lang) // Clean up each language tag
}
return parts
}
// ContentType returns the Content-Type header value.
func (c *Context) ContentType() string {
return c.request.Header.Get(constContentTypeHeader)
}
// Form retrieves a form value after parsing the form data.
func (c *Context) Form(key string) string {
_ = c.request.ParseForm() // Parse form if not already done
return c.request.FormValue(key)
}
// FormValue retrieves a form value, including multipart form data.
func (c *Context) FormValue(key string) string {
_ = c.request.ParseMultipartForm(c.okapi.maxMultipartMemory) // Parse multipart form
return c.request.FormValue(key)
}
// FormFile retrieves a file from multipart form data.
// Returns the file and any error encountered.
func (c *Context) FormFile(key string) (*multipart.FileHeader, error) {
_ = c.request.ParseMultipartForm(c.okapi.maxMultipartMemory)
f, fh, err := c.request.FormFile(key)
if err != nil {
return nil, err
}
err = f.Close()
if err != nil {
return nil, err
}
return fh, err
}
// Cookie retrieves a cookie value by name.
// Returns empty string and error if cookie not found.
func (c *Context) Cookie(name string) (string, error) {
cookie, err := c.request.Cookie(name)
if err != nil {
return "", err
}
return cookie.Value, nil
}
// SetCookie sets a cookie with various configurable options.
// Defaults path to "/" if empty.
func (c *Context) SetCookie(name, value string, maxAge int, path, domain string, secure, httpOnly bool) {
if path == "" {
path = "/" // Default path to root
}
http.SetCookie(c.response, &http.Cookie{
Name: name,
Value: url.QueryEscape(value), // URL-encode cookie value
MaxAge: maxAge,
Path: path,
Domain: domain,
Secure: secure,
HttpOnly: httpOnly,
})
}
// IsWebSocketUpgrade checks if the request is a WebSocket upgrade request.
func (c *Context) IsWebSocketUpgrade() bool {
// Check if the request is a WebSocket upgrade request
return c.request.Header.Get("Upgrade") == "websocket" && c.request.Method == http.MethodGet
}
// IsSSE checks if the request is for Server-Sent Events (SSE).
func (c *Context) IsSSE() bool {
// Check if the request is for Server-Sent Events
return c.request.Header.Get("Accept") == "text/event-stream" && c.request.Method == http.MethodGet
}
// ************* response Utilities *************
// SetHeader sets a response header.
func (c *Context) SetHeader(key, value string) {
c.response.Header().Set(key, value)
}
// Header gets a request header by key.
func (c *Context) Header(key string) string {
return c.request.Header.Get(key)
}
// Headers returns all request headers as a map.
func (c *Context) Headers() map[string][]string {
return c.request.Header
}
// WriteStatus writes the HTTP status code to the response.
func (c *Context) WriteStatus(code int) {
c.response.WriteHeader(code)
}
// writeResponse is a helper for writing responses with common headers and status.
// Takes care of content type, status code, and error handling.
func (c *Context) writeResponse(code int, contentType string, writeFunc func() error) error {
c.response.Header().Set(constContentTypeHeader, contentType)
c.response.WriteHeader(code)
if err := writeFunc(); err != nil {
http.Error(c.response, err.Error(), http.StatusInternalServerError)
return err
}
return nil
}
// JSON writes a JSON response with the given status code.
func (c *Context) JSON(code int, v any) error {
return c.writeResponse(code, constJSON, func() error {
return json.NewEncoder(c.response).Encode(v)
})
}
func (c *Context) jsonProblemError(code int, v any) error {
return c.writeResponse(code, constJSONProblem, func() error {
return json.NewEncoder(c.response).Encode(v)
})
}
func (c *Context) xmlProblemError(code int, v any) error {
return c.writeResponse(code, constXMLProblem, func() error {
return xml.NewEncoder(c.response).Encode(v)
})
}
// OK writes a JSON response with 200 status code.
func (c *Context) OK(v any) error {
return c.JSON(http.StatusOK, v)
}
// NoContent returns an empty response body with status code 204
func (c *Context) NoContent() error {
return c.String(http.StatusNoContent, "")
}
// Created writes a JSON response with 201 status code.
func (c *Context) Created(v any) error {
return c.JSON(http.StatusCreated, v)
}
// XML writes an XML response with the given status code.
func (c *Context) XML(code int, v any) error {
return c.writeResponse(code, constXML, func() error {
return xml.NewEncoder(c.response).Encode(v)
})
}
// YAML writes a YAML response with the given status code.
func (c *Context) YAML(code int, data any) error {
return c.writeResponse(code, constYAML, func() error {
return yaml.NewEncoder(c.response).Encode(data)
})
}
// Text writes a plain text response with the given status code.
func (c *Context) Text(code int, v any) error {
return c.writeResponse(code, constPLAINTEXT, func() error {
_, err := fmt.Fprint(c.response, v)
return err
})
}
// ************* Server-Sent Events (SSE) ***************
// sendSSE writes an SSE response with optional ID.
func (c *Context) sendSSE(id, eventType string, message any) error {
msg := Message{
ID: id,
Event: eventType,
Data: message,
}
_, err := msg.Send(c.response)
return err
}
// SSEvent writes SSE response with optional ID.
func (c *Context) SSEvent(eventType string, data any) error {
return c.sendSSE("", eventType, data)
}
// SendSSEvent writes SSE response with an ID.
// Deprecated: use SSESendEvent instead.
func (c *Context) SendSSEvent(id, eventType string, data any) error {
return c.sendSSE(id, eventType, data)
}
// SSESendEvent writes SSE response with an ID.
func (c *Context) SSESendEvent(id, eventType string, data any) error {
return c.sendSSE(id, eventType, data)
}
// SSEStream keeps connection open for multiple messages
func (c *Context) SSEStream(ctx context.Context, messageChan <-chan Message) error {
// Set SSE headers and flush immediately
(&Message{}).setSSEHeaders(c.response)
if flusher, ok := c.response.(http.Flusher); ok {
flusher.Flush()
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case msg := <-messageChan:
if _, err := msg.Send(c.response); err != nil {
return err
}
}
}
}
// SSESendData sends structured data as JSON
func (c *Context) SSESendData(data any) error {
msg := Message{
Data: data,
}
_, err := msg.Send(c.response)
return err
}
// SSESendJSON sends JSON data with explicit JSON serialization
func (c *Context) SSESendJSON(data any) error {
msg := Message{
Data: data,
Serializer: JSONSerializer{},
}
_, err := msg.Send(c.response)
return err
}
// SSESendText sends plain text data
func (c *Context) SSESendText(text string) error {
msg := Message{
Data: text,
Serializer: TextSerializer{},
}
_, err := msg.Send(c.response)
return err
}
// SSESendBinary sends binary data as base64
func (c *Context) SSESendBinary(data []byte) error {
msg := Message{
Data: data,
Serializer: Base64Serializer{},
}
_, err := msg.Send(c.response)
return err
}
// SendSSECustom sends data with custom serializer
func (c *Context) SendSSECustom(data any, serializer Serializer) error {
msg := Message{
Data: data,
Serializer: serializer,
}
_, err := msg.Send(c.response)
return err
}
// SSEStreamWithOptions provides advanced streaming control
func (c *Context) SSEStreamWithOptions(ctx context.Context, messageChan <-chan Message, opts *StreamOptions) error {
if opts == nil {
opts = &StreamOptions{}
}
// Set SSE headers and flush immediately
(&Message{}).setSSEHeaders(c.response)
if flusher, ok := c.response.(http.Flusher); ok {
flusher.Flush()
}
var ticker *time.Ticker
var pingChan <-chan time.Time
if opts.PingInterval > 0 {
ticker = time.NewTicker(opts.PingInterval)
defer ticker.Stop()
pingChan = ticker.C
}
for {
select {
case <-ctx.Done():
return ctx.Err()
case <-pingChan:
// Send comment line to keep connection alive
if _, err := fmt.Fprint(c.response, ": ping\n\n"); err != nil {
if opts.OnError != nil {
opts.OnError(err)
}
return err
}
if flusher, ok := c.response.(http.Flusher); ok {
flusher.Flush()
}
case msg, ok := <-messageChan:
if !ok {
return nil
}
if msg.Serializer == nil && opts.Serializer != nil {
msg.Serializer = opts.Serializer
}
if _, err := msg.Send(c.response); err != nil {
if opts.OnError != nil {
opts.OnError(err)
}
return err
}
}
}
}
// String is an alias for Text for convenience.
func (c *Context) String(code int, data any) error {
return c.Text(code, data)
}
// Data writes a raw byte response with the given content type and status code.
func (c *Context) Data(code int, contentType string, data []byte) error {
return c.writeResponse(code, contentType, func() error {
_, err := c.response.Write(data)
return err
})
}
// HTML renders an HTML template from a file with the given status code.
func (c *Context) HTML(code int, file string, data any) error {
tmpl, err := template.ParseFiles(file) // Parse template file
if err != nil {
return err
}
return c.renderHTML(code, tmpl, data)
}
// HTMLView renders an HTML template from a string with the given status code.
func (c *Context) HTMLView(code int, templateStr string, data any) error {
tmpl, err := template.New("inline").Parse(templateStr) // Parse template string
if err != nil {
return err
}
return c.renderHTML(code, tmpl, data)
}
// Render renders a template using the configured Renderer.
func (c *Context) Render(code int, name string, data interface{}) error {
if c.okapi.renderer == nil {
return ErrNoRenderer
}
if name == "" {
return c.writeResponse(code, constHTML, func() error {
return c.okapi.renderer.Render(c.response, "", nil, c)
})
}
return c.writeResponse(code, constHTML, func() error {
return c.okapi.renderer.Render(c.response, name, data, c)
})
}
// renderHTML is a helper for rendering HTML templates.
func (c *Context) renderHTML(code int, tmpl *template.Template, data any) error {
return c.writeResponse(code, constHTML, func() error {
return tmpl.Execute(c.response, data) // Execute template with data
})
}
// Redirect sends a redirect response to the specified location.
func (c *Context) Redirect(code int, location string) {
c.SetHeader(constLocationHeader, location) // Set Location header
c.WriteStatus(code) // Write status code
_, _ = fmt.Fprintf(c.response, "Redirecting to %s", location) // Optional message
}
// *********** File Serving **************
// ServeFile serves a file from the filesystem.
func (c *Context) ServeFile(path string) {
http.ServeFile(c.response, c.request, path) // Use standard library file server
}
// ServeFileFromFS serves a file from a custom http.FileSystem.
func (c *Context) ServeFileFromFS(filepath string, fs http.FileSystem) {
// Sanitize the path to prevent directory traversal
filepath = path.Clean(filepath)
if filepath == "." || strings.Contains(filepath, "..") {
err := c.ErrorNotFound("Not found")
if err != nil {
return
}
}
// Preserve original URL.Path
oldPath := c.request.URL.Path
defer func() { c.request.URL.Path = oldPath }()
c.request.URL.Path = filepath
http.FileServer(fs).ServeHTTP(c.response, c.request)
}
// ServeFileAttachment serves a file as an attachment (download).
func (c *Context) ServeFileAttachment(path, filename string) {
c.SetHeader("Content-Disposition", fmt.Sprintf("attachment; filename=%q", filename))
http.ServeFile(c.response, c.request, path)
}
// ServeFileInline serves a file to be displayed inline in the browser.
func (c *Context) ServeFileInline(path, filename string) {
c.SetHeader("Content-Disposition", fmt.Sprintf("inline; filename=%q", filename))
http.ServeFile(c.response, c.request, path)
}
// *********** MultipartMemory **************
// MaxMultipartMemory returns the maximum memory for multipart form
func (c *Context) MaxMultipartMemory() int64 {
return c.okapi.maxMultipartMemory
}
// SetMaxMultipartMemory sets the maximum memory for multipart form (default: 32 MB)
func (c *Context) SetMaxMultipartMemory(max int64) {
if max > 0 {
c.okapi.maxMultipartMemory = max
}
}
// ******************* Output ********************
// Return is an alias for Respond to improve readability when sending output.
func (c *Context) Return(output any) error {
return c.Respond(output)
}
// Respond serializes the output struct into the HTTP response.
// It inspects struct tags to automatically set headers, cookies, and status code,
// and encodes the response body in the format requested by the `Accept` header.
//
// Supported formats: JSON, XML, YAML, plain text, HTML.
//
// Example:
//
// type BookResponse struct {
// Status int // HTTP status code
// version string `header:"version"` // Response header
// Session string `cookie:"SessionID"` // Response cookie
// Body struct {
// ID int `json:"id"`
// Name string `json:"name"`
// Price int `json:"price"`
// }
// }
//
// okapi.Get("/books/:id", func(c okapi.Context) error {
// return c.Respond(BookResponse{
// version: "v1",
// Session: "abc123",
// Status: 200,
// Body: struct {
// ID int `json:"id"`
// Name string `json:"name"`
// Price int `json:"price"`
// }{
// ID: 1, Name: "Okapi Guide", Price: 50,
// },
// })
// })
func (c *Context) Respond(output any) error {
v := reflect.ValueOf(output)
if !v.IsValid() {
return c.AbortInternalServerError("Internal Server Error", fmt.Errorf("output is nil"))
}
// Dereference pointer if needed
if v.Kind() == reflect.Ptr {
if v.IsNil() {
return c.AbortInternalServerError("Internal Server Error", fmt.Errorf("output is nil pointer"))
}
v = v.Elem()
}
t := v.Type()
if t.Kind() != reflect.Struct {
return c.AbortInternalServerError("Internal Server Error", fmt.Errorf("output must be a struct"))
}
status := getResponseStatus(v)
for i := 0; i < t.NumField(); i++ {
field := t.Field(i)
val := v.Field(i).Interface()
// Header tag
if header := field.Tag.Get(tagHeader); header != "" {
c.Response().Header().Set(header, fmt.Sprint(val))
continue
}
// Cookie tag
if cookie := field.Tag.Get(tagCookie); cookie != "" {
http.SetCookie(c.Response(), &http.Cookie{
Name: cookie,
Value: fmt.Sprint(val),
Path: "/",
})
continue
}
// Fallback: expose non-status, non-body fields as headers
if field.Name != "Status" && field.Name != bodyField {
key := field.Name
if jsonTag := field.Tag.Get(tagJSON); jsonTag != "" && jsonTag != "-" {
key = strings.Split(jsonTag, ",")[0]
}
c.Response().Header().Set(key, fmt.Sprint(val))
}
}
var body any
if f := v.FieldByName(bodyField); f.IsValid() {
body = f.Interface()
}
accept := c.request.Header.Get("Accept")
switch {
case strings.Contains(accept, constXML):
return c.XML(status, body)
case strings.Contains(accept, constYAML), strings.Contains(accept, constYamlText), strings.Contains(accept, constYamlX):
return c.YAML(status, body)
case strings.Contains(accept, constJSON):
return c.JSON(status, body)
case strings.Contains(accept, constPLAINTEXT), strings.Contains(accept, constHTML):
return c.String(status, body)
default:
return c.JSON(status, body)
}
}
// NewContext creates a new Okapi Context
func NewContext(o *Okapi, w http.ResponseWriter, r *http.Request) *Context {
if o == nil {
Default()
}
return &Context{
request: r,
okapi: o,
response: newResponseWriter(w),
store: newStoreData(),
}
}
// ************ Errors in errors.go *****************