about summary refs log tree commit diff stats
path: root/lua/sandborb/route_handler.lua
blob: f28c9499b6d3f1a7a3cc08571ce7055fe7495807 (plain) (blame)
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
local json = require "json"
local giblang = require "giblang"

local function brackets(e)
  return {
    content_type = "application/json",
    body = json.encode({ 1, 2, 3, { x = 10 } })
  }
end

local function banana(e)
  return {
    content_type = "text/html, charset=utf-8",
    body = "<h1>Bananas are delicious!</h1>"
  }
end

local function gib(e,n)
  return {
    content_type = "text/html, charset=utf-8",
    body = "<h1>" .. giblang.speak(n) .. "</h1>"
  }
end

local function teapot(e)
  return {
    code = 418,
    status = "I'm a teapot",
    content_type = "text/html, charset=utf-8",
    body = "<h1>I'm a teapot!</h1>"
  }
end

local function error_404(e, p)
  return {
    code = 404,
    status = "Not Found",
    content_type = "text/html, charset=utf-8",
    body = "<h1>404 - Page not found: " .. p .. "</h1>"
  }
end

function HANDLE_ROUTE(e, path)
  local response = {
    content_type = "text/html, charset=utf-8",
    body = ""
  }

  if path == "/" then
    response.body = "Hello, you are at the root!"
  elseif path == "/about" then
    response.body = "This is the about page!"
  elseif path == "/banana" then
    response = banana(e)
  elseif path == "/json" then
    response = brackets(e)
  elseif path == "/giblang" then
    math.randomseed(os.time())
    local number_of_words = math.random(2, 10)
    response = gib(e, number_of_words)
  elseif path == "/teapot" then
    response = teapot(e)
  else
    response = error_404(e, path)
  end

  if not response.code then
    response.status = "OK"
    response.code = 200
  end

  sb_send_status(e, response.code, response.status)
  sb_send_header(e, "Content-Type", response.content_type)
  return response.body
end


function HANDLE_POST_ROUTE(e, path) -- FIXME: I'm not currently passing the body of the POST request, not sure how to access it from C
  local response = {
    content_type = "text/plain",
    body = ""
  }

  if path == "/echo" then
    response = {
      body = "server response: " .. path
    }
  else
    response = error_404(e, path)
  end

  if not response.code then
    response.status = "OK"
    response.code = 200
  end

  sb_send_status(e, response.code, response.status)
  sb_send_header(e, "Content-Type", response.content_type)
  return response.body
end