Get input from user with Rascal

Viewed 85

Rascal is currently hosting my simple web server. Here I have an input for users using HTML textarea tag, and a submit button. However, I can't figure out how to request that input data from users when they have submitted it. I also don't see much documentation about it, so any help would be appreciated!

1 Answers

Assuming you either use the Content and/or util::Webserver from the library for serving content from Rascal, you always provide a function of type Response (Request) to the server. This function does everything from serving index.html to receiving form inputs, and handling XMLHttpRequests. All you have to do is write the function's alternatives.

The kinds of Requests you can get are defined like this in Content.rsc:

data Request (map[str, str] headers = (), map[str, str] parameters = (), map[str,str] uploads = ())
  = get (str path)
  | put (str path, Body content)
  | post(str path, Body content)
  | delete(str path)
  | head(str path)
  ;

And responses are defined by:

data Response 
  = response(Status status, str mimeType, map[str,str] header, str content)
  | fileResponse(loc file, str mimeType, map[str,str] header)
  | jsonResponse(Status status, map[str,str] header, value val, bool implicitConstructors = true,  bool implicitNodes = true, str dateTimeFormat = "yyyy-MM-dd\'T\'HH:mm:ss\'Z\'")
  ;

In the example below I use convenience utility functions such as Content::response(str) which wrap an html string with the right HTTP status and mimetypes.

Example:

// this serves the initial form
Response myServer(get("/")) 
  = response("\<p\>What is your name?\</p\>
             '\<form action=\"/submit\" method=\"GET\"\>
             '   \<input type=\"text\" name=\"name\" value=\"\"\>
             '\</form\>
             ");   

// // this responds to the form submission, now using a function body with a return (just for fun):
Response myServer(p:get("/submit")) {
   return response("Hello <p.parameters["name"]>!");
}

// in case of failing to handle a request, we dump the request back for debugging purposes:
default Response myServer(Request q) = response("<q>");

Now we can serve this directly from the REPL. The content will show up in an Eclipse editor window or in your default browser and will stay available for 30 minutes after the last interaction in Rascal's internal application server:

rascal>content("test", myServer)
Serving 'test' at |http://localhost:9050/|

Or we can serve it on our own, then browse to http://localhost:10001 to test the server. We have to shut the thing down manually when we're done:

rascal>import util::Webserver;
ok
rascal>serve(|http://localhost:10001|, myServer)
ok
rascal>shutdown(|http://localhost:10001|)

The initially served page in an editor window

The response after for submission

Related