NOTE This is not an official product of Perfect. However, Squishy is an independent parser library which can translate a "squishy" file into a Perfect Swift handler.
A squishy file looks like this - yes, it is a Swift-style hyper text preprocessor:
<%
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
func add(a: Int, b: Int) -> {
return a + b
}
%>
<HTML><HEAD><META CHARSET="UTF-8">
<TITLE>测试脚本</TITLE>
</HEAD><BODY>
<?
let x = UUID()
let y = "\(x)"
response.setHeader(.contentType, value: "text/html")
?>
<H1>你好! \(y) 和 \(add(a: 1, b: 2))</H1>
</BODY></HTML>
and the outcome of translation would look like:
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer
func add(a: Int, b: Int) -> {
return a + b
}
func handlerX(data: [String:Any]) throws -> RequestHandler { return {
request, response in
response.appendBody(string:
"""
<HTML><HEAD><META CHARSET=\"UTF-8\">
<TITLE>测试脚本</TITLE>
</HEAD><BODY>
"""
)
let x = UUID()
let y = "\(x)"
response.setHeader(.contentType, value: "text/html")
response.appendBody(string:
"""
<H1>你好! \(y) 和 \(add(a: 1, b: 2))</H1>
</BODY></HTML>
"""
)
response.completed()
}
}
A Squishy web page can have three different types of scripts natively:
- HTML. This is the default format. NOTE The only feature you may take interests here is that Swift Interpolation
\(variable)
is available here. - Global Swift Code. Content marked inside
<% ... %>
will be translated into a swift program in the current name space. - Perfect Route Handler. Content that marked with
<? ... ?>
will be treated as a standard named Perfect Route Handler, where the two key variablesrequest: HTTPRequest
andresponse: HTTPResponse
are available in this section.
Swift 4.0 toolchain.
.package(url: "https://github.com/RockfordWei/Perfect-Squishy.git",
from: "1.0.1")
...
dependencies: ["PerfectSquishy"]
The following snippet can translate the above "x.squishy" file into "y.swift":
import PerfectSquishy
let from = "x.squishy"
let to = "y.swift"
let parser = Squishy(handler: "handlerX", from: from, to: to)
try parser.parse()
For more information on the Perfect project, please visit perfect.org.