aboutsummaryrefslogtreecommitdiff
path: root/utils/meta/request.go
blob: 98d277ef1bba9987dc66ffabb273b878ed3f6ed5 (plain)
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
package meta

import (
	"metachan/types"
	"metachan/utils/logger"

	"github.com/gofiber/fiber/v2"
)

const requestKey = "__request_ctx"

func Request(c *fiber.Ctx) facade {
	req, ok := c.Locals(requestKey).(types.Request)
	if !ok {
		logger.Errorf("META", "RequestContext missing in fiber locals")
		return facade{}
	}
	return facade{req: req, ctx: c}
}

func (f facade) Param(key string) (string, bool) {
	if f.ctx != nil {
		val := f.ctx.Params(key)
		if val != "" {
			return val, true
		}
	}
	return "", false
}

func (f facade) Query(key string) (string, bool) {
	for _, q := range f.req.Query {
		if q.Key == key {
			return q.Value, true
		}
	}
	return "", false
}

func (f facade) Header(key string) (string, bool) {
	for _, h := range f.req.Headers {
		if h.Key == key {
			return h.Value, true
		}
	}
	return "", false
}

func (r required) Param(key string) string {
	// Access params directly from fiber context (available after route matching)
	if r.ctx != nil {
		val := r.ctx.Params(key)
		if val != "" {
			return val
		}
	}
	logger.Errorf("META", "missing required param: %s", key)
	return ""
}

func (r required) Query(key string) string {
	for _, q := range r.req.Query {
		if q.Key == key {
			return q.Value
		}
	}
	logger.Errorf("META", "missing required query: %s", key)
	return ""
}

func (r required) Header(key string) string {
	for _, h := range r.req.Headers {
		if h.Key == key {
			return h.Value
		}
	}
	logger.Errorf("META", "missing required header: %s", key)
	return ""
}

func (d withDefault) Param(key string) string {
	// Access params directly from fiber context (available after route matching)
	if d.ctx != nil {
		val := d.ctx.Params(key)
		if val != "" {
			return val
		}
	}
	return d.def
}

func (d withDefault) Query(key string) string {
	for _, q := range d.req.Query {
		if q.Key == key {
			return q.Value
		}
	}
	return d.def
}

func (d withDefault) Header(key string) string {
	for _, h := range d.req.Headers {
		if h.Key == key {
			return h.Value
		}
	}
	return d.def
}