使用 Rascal 从用户那里获取输入

Get input from user with Rascal

Rascal 目前正在托管我的简单网络服务器。在这里,我为使用 HTML textarea 标签的用户提供了一个输入,以及一个提交按钮。但是,我无法弄清楚如何在用户提交输入数据后向他们请求输入数据。我也没有看到太多关于它的文档,所以任何帮助将不胜感激!

假设您使用库中的 Content and/or util::Webserver 来提供来自 Rascal 的内容,您总是向服务器提供 Response (Request) 类型的函数。这个函数做 一切 从服务 index.html 到接收表单输入,以及处理 XMLHttpRequests。您所要做的就是编写函数的替代项。

Content.rsc中,您可以得到的Request种类是这样定义的:

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)
  ;

响应定义为:

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\'")
  ;

在下面的示例中,我使用了方便的实用程序函数,例如 Content::response(str),它用正确的 HTTP 状态和 mimetypes 包装了一个 html 字符串。

示例:

// 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>");

现在我们可以直接从 REPL 提供它。内容将显示在 Eclipse 编辑器 window 或您的默认浏览器中,并在 Rascal 的内部应用程序服务器中最后一次交互后保持可用 30 分钟:

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

或者我们可以自己提供服务,然后浏览到 http://localhost:10001 来测试服务器。我们必须在完成后手动关闭它:

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