上篇文章中,自己完成了perfect框架的clone,着急着写代码,但是看着添加路由中的url路径,开始懵逼....疯狂地探索...
路由
关于什么是路由?这里先贴一官网地址https://www.perfect.org/docs/routing_zh_CN.html,里面有详细描述。
不理解在于route.add(method,url,handle)其中的url与handle之间的关系是怎样?https://www.perfect.org/docs/repositoryLayout_zh_CN.html中提到有典型的例子,可惜 点击链接(https://github.com/PerfectlySoft/PerfectExamples)告诉我 404,瞬间泪奔...可能是自身信息检索学的垃圾,检索不到自己想要的结果,索性就自我不断的尝试,终于.....有了结果
url VS handle
三言两语就搞定,url 即是:http(s)://xxxx/api/login 当中的api/login,可以任意规定,也就是说api/login是一个标志,当访问这个地址时就走handle回调。
实例结构图
WX20201230-161223.pngmain.swift 代码
import PerfectHTTP
import PerfectHTTPServer
var routes = Routes()
routes.add(method: .post, uri: "api/login", handler: login().loginhandle)
try HTTPServer.launch(name: "localhost",
port: 8383,
routes: routes,
responseFilters: [
(PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])
login.swift代码 只为测试哈 代码很冗余 嘿嘿
import PerfectHTTP
import PerfectHTTPServer
public struct login{
public func loginhandle(request:HTTPRequest,response:HTTPResponse) -> Void{
let tel:String? = request.param(name: "tel")
let pw:String? = request.param(name: "pw")
guard let phone = tel else {
var result = Dictionary<String, Any>()
result.updateValue("tel can't be null", forKey: "msg")
result.updateValue(0, forKey: "code")
guard let jsonString = try? result.jsonEncodedString() else {
return
}
response.setBody(string: jsonString)
response.completed()
return
}
guard let password = pw else {
var result = Dictionary<String, Any>()
result.updateValue("pw can't be null", forKey: "msg")
result.updateValue(0, forKey: "code")
guard let jsonString = try? result.jsonEncodedString() else {
return
}
response.setBody(string: jsonString)
response.completed()
return
}
var result = Dictionary<String, Any>()
result.updateValue(1, forKey: "code")
result.updateValue("登录成功", forKey: "msg")
result.updateValue(["phone":phone,"password":password.uppercased()], forKey: "data")
guard let jsonString = try? result.jsonEncodedString() else {
return
}
response.setBody(string: jsonString)
response.completed()
return
}
}
测试
用postman 进行测试 地址:http://localhost:8383/api/login ,如下图:
搞定。。。手工 后续进行数据库连接测试
网友评论