'Class module
Sub Class_Globals
End Sub
Public Sub Initialize
End Sub
Sub Handle(req As ServletRequest, resp As ServletResponse)
Log(req.FullRequestURI)
Select Case req.Method
Case "GET"
' retrieve the path after /demo
Dim Path As String = req.RequestURI.SubString("/demo/".Length)
' remove the parameters (if any) from the path
Dim index As Int = Path.IndexOf("?")
If index > 0 Then
Path = Path.SubString2(0,index)
End If
' check the paths and act acoordingly
Select Case Path
Case "getdatetime" ' /demo/getdatetime
' give our answer back
resp.Status = 200
resp.Write($"{"currentDateTime": "${DateTime.Date(DateTime.now)} ${DateTime.Time(DateTime.now)}"}"$)
Return
Case "echoparams" ' /demo/echoparams?param1=1¶m2=Test
' get all the params and convert to json to echo
Dim json As String = ParametersToJson(req.ParameterMap)
' give our answer back
resp.Status = 200
resp.Write($"{"currentDateTime": "${DateTime.Date(DateTime.now)} ${DateTime.Time(DateTime.now)}", "params": ${json}}"$)
Return
Case Else
Log("GET: unknown Path")
resp.Status = 404
resp.write("Invalid call")
Return
End Select
Case "POST"
' retrieve the path after /demo
Dim Path As String = req.RequestURI.SubString("/demo/".Length)
Select Case Path
Case "echobody" ' /demo/echobody
' get the json body
Dim bodyJson As String
Dim bodyReader As TextReader
bodyReader.Initialize(req.InputStream)
bodyJson = bodyReader.ReadAll
' give our answer back
resp.Status = 200
resp.Write($"{"currentDateTime": "${DateTime.Date(DateTime.now)} ${DateTime.Time(DateTime.now)}", "echoBody": ${bodyJson}}"$)
Return
Case Else
Log("POST: unknown Path")
resp.Status = 404
resp.write("Invalid call")
End Select
Case Else
Log("unknown METHOD")
resp.Status = 404
resp.write("Invalid call")
Return
End Select
End Sub
' helper method to convert the body to json
Public Sub ParametersToJson (paramsM As Map) As String
Dim params As String = "["
For Each name As String In paramsM.Keys
If params <> "[" Then
params = params & ","
End If
Dim Vals As String
Dim values() As String = paramsM.Get(name)
For Each value As String In values
If Vals <> "" Then
Vals = Vals & " "
End If
Vals = Vals & value
Next
If IsNumber(Vals) Or Vals.ToLowerCase = "true" Or Vals.ToLowerCase = "false" Then
params = params & "{" & Chr(34) & name & Chr(34) & ": " & Vals & "}"
Else
params = params & "{" & Chr(34) & name & Chr(34) & ": " & Chr(34) & Vals & Chr(34) & "}"
End If
Next
params = params & "]"
Return params
End Sub