-
Notifications
You must be signed in to change notification settings - Fork 0
/
header.go
128 lines (102 loc) · 2.24 KB
/
header.go
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
package fasthttp
import (
"errors"
"github.com/rock-go/rock/lua"
"strings"
)
type headerKV struct {
key string
val string
}
type header struct {
lua.Super
data []headerKV
}
func (h *header) Type() string {
return "fasthttp.header"
}
func (h *header) Name() string {
return h.Type()
}
func (h *header) Len() int {
return len(h.data)
}
func (h *header) Set(key string, val string) {
n := h.Len()
for i := 0; i < n; i++ {
item := &h.data[i]
if strings.EqualFold(item.key, key) {
item.key = key
item.val = val
return
}
}
h.data = append(h.data, headerKV{key, val})
}
func (h *header) ForEach(fn func(string, string)) {
n := h.Len()
for i := 0; i < n; i++ {
item := &h.data[i]
fn(item.key, item.val)
}
}
func newHeader() *header {
return &header{}
}
func toHeader(L *lua.LState , val lua.LValue) *header {
if val.Type() != lua.LTTable {
L.RaiseError("header must be table")
return nil
}
tab := val.(*lua.LTable)
h := newHeader()
tab.ForEach(func(key lua.LValue, val lua.LValue) {
if key.Type() != lua.LTString {
L.RaiseError("fasthttp header must be table , got array")
return
}
switch val.Type() {
case lua.LTString:
h.Set(key.String(), val.String())
case lua.LTNumber:
h.Set(key.String(), val.String())
default:
L.RaiseError("invalid header , must be string , got %s", val.Type().String())
}
})
return h
}
func newLuaHeader(L *lua.LState) int {
tab := L.CheckTable(1)
h := newHeader()
tab.ForEach(func(key lua.LValue, val lua.LValue) {
if key.Type() != lua.LTString {
L.RaiseError("fasthttp header must be table , got array")
return
}
switch val.Type() {
case lua.LTString:
h.Set(key.String(), val.String())
case lua.LTNumber:
h.Set(key.String(), val.String())
default:
L.RaiseError("invalid header , must be string , got %s", val.Type().String())
}
})
L.Push(L.NewAnyData(h))
return 1
}
var (
invalidHeaderType = errors.New("invalid header type , must be userdata")
invalidHeaderValue = errors.New("invalid header value")
)
func checkHeader(val lua.LValue) (*header, error) {
if val.Type() != lua.LTANYDATA {
return nil, invalidHeaderType
}
h, ok := val.(*lua.AnyData).Value.(*header)
if !ok {
return nil, invalidHeaderValue
}
return h, nil
}