PerfectTemplate 简体中文

Get Involed with Perfect!

Star Perfect On Github Stack Overflow Follow Perfect on Twitter Join the Perfect Slack

Swift 5.0 Platforms macOS | Linux License Apache PerfectlySoft Twitter Slack Status

Perfect 空白启动项目

此仓库包含一个空白的 Perfect 项目,可以克隆它作为新项目的起点。它使用 Swift Package Manager 构建,并生成一个独立的 HTTP 可执行文件。

Swift 兼容性

此项目的主分支目前可以在 Ubuntu 上使用 Xcode 10Swift 4.1 或更高版本的工具链进行编译。

构建 & 运行

以下命令将克隆并构建一个空白启动项目,并在端口 8181 上启动服务器。

git clone https://github.com/PerfectlySoft/PerfectTemplate.git
cd PerfectTemplate
swift run

您应该看到以下输出

[INFO] Starting HTTP server localhost on 0.0.0.0:8181

这意味着服务器正在运行并等待连接。访问 https://:8181/ 以查看问候语。按下 control-c 终止服务器。

启动内容

模板文件包含一个简单的 "hello, world!" 请求处理程序,并展示了如何提供静态文件以及压缩传出内容。

import PerfectHTTP
import PerfectHTTPServer

// An example request handler.
// This 'handler' function can be referenced directly in the configuration below.
func handler(request: HTTPRequest, response: HTTPResponse) {
	// Respond with a simple message.
	response.setHeader(.contentType, value: "text/html")
	response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>")
	// Ensure that response.completed() is called when your processing is done.
	response.completed()
}

// Configure one server which:
//	* Serves the hello world message at <host>:<port>/
//	* Serves static files out of the "./webroot"
//		directory (which must be located in the current working directory).
//	* Performs content compression on outgoing data when appropriate.
var routes = Routes()
routes.add(method: .get, uri: "/", handler: handler)
routes.add(method: .get, uri: "/**",
		   handler: StaticFileHandler(documentRoot: "./webroot", allowResponseFilters: true).handleRequest)
try HTTPServer.launch(name: "localhost",
					  port: 8181,
					  routes: routes,
					  responseFilters: [
						(PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])

更多信息

有关 Perfect 项目的更多信息,请访问 perfect.org