forked from tlrobinson/martin.sh
-
Notifications
You must be signed in to change notification settings - Fork 1
/
martin.sh
82 lines (66 loc) · 1.49 KB
/
martin.sh
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
. wwwoosh.sh
martin_response="/tmp/martin_response"
routes_method=()
routes_path=()
routes_action=()
route () {
routes_method=( ${routes_method[@]} "$1" )
routes_path=( ${routes_path[@]} "$2" )
routes_action=( ${routes_action[@]} "$3" )
}
get () {
route "GET" $@
}
post () {
route "POST" $@
}
delete () {
route "DELETE" $@
}
status () {
response_status="$1"
}
header () {
head="$1: $2"
if [ "$response_headers" ]; then
response_headers="$response_headers\n$head"
else
response_headers="$head"
fi
}
not_found () {
status "404"
header "Content-type" "text/plain"
if [ $# -gt 0 ]; then
echo "$@"
else
echo "Not Found: $PATH_INFO"
fi
}
martin_dispatch () {
action=""
for (( i = 0 ; i < ${#routes_method[@]} ; i++ )); do
method=${routes_method[$i]}
path=${routes_path[$i]}
act=${routes_action[$i]}
if [ "$REQUEST_METHOD" = "$method" ]; then
if [ "$PATH_INFO" = "$path" ]; then
action="$act"
break
fi
fi
done
[ ! "$action" ] && action="not_found"
reset_response
# execute the action, storing output in a temporary file
"$action" > "$martin_response"
# set status header, echo headers, blank line, then body
header "Status" "$response_status"
echo -e "$response_headers"
echo ""
cat "$martin_response"
}
reset_response () {
response_status="200 OK"
response_headers=""
}