Perfect 网络篇

添加依赖包

打开Package.swift 文件替换内容, 加入PerfectHTTPServer, PerfectMySQL, PerfectMustache依赖包

注意坑: 上面注释不能删除PerfectMySQL依赖包添加后代码报错,需要给mysql 降版本方能兼容

// swift-tools-version:5.0
// The swift-tools-version declares the minimum version of Swift required to build this package.
//亲测:上面注释不能删除

/**
 * Perfect-MySQL 编译错误解决方法
 * 卸载MySQL
 * brew uninstall mysql
 * brew install [email protected]
 * brew install [email protected] && brew link [email protected] --force
 * 安装成功后: swift build
 * 重新生成包: swift package generate-xcodeproj
 */
import PackageDescription

let package = Package(
    name: "PerfectDemo",
    dependencies: [
        .package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", from: "3.0.0"),
        .package(url: "https://github.com/PerfectlySoft/Perfect-MySQL.git", from: "3.0.0"),
        .package(url: "https://github.com/PerfectlySoft/Perfect-Mustache.git", from: "3.0.0")
    ],
    targets: [
        .target(
            name: "PerfectDemo",
            dependencies: ["PerfectHTTPServer", "PerfectMySQL", "PerfectMustache"]),
    ]
)

注意: 每次新导入依赖包,都必须重新 执行 swift build , swift package generate-xcodeproj 生成新的依赖关系

创建网络工具类

创建sever, 注册,添加路由,过滤404等功能

//
//  NetworkServerManager.swift
//  COpenSSL
//
//  Created by apple on 2019/7/1.
//

import Foundation
import PerfectLib
import PerfectHTTP
import PerfectHTTPServer

open class NetworkServerManager {
//    open > public > interal > fileprivate > private 访问权限
//    interal 默认,可以别外部调用,集成
    fileprivate var server: HTTPServer = HTTPServer.init() //服务器
    internal init(root: String, port: uint16, routesArray: Array>) {
        for dict: Dictionary in routesArray {
            let baseURL: String = dict["url"] as! String // 根地址
            let method: String = dict["method"] as! String //方法
            var routes = Routes.init(baseUri: baseURL)     //创建路由器
            let httpMethod = HTTPMethod.from(string: method)
            configure(routes: &routes, method: httpMethod)   //注册路由
            server.addRoutes(routes) // 路由添加到服务
        }
        server.serverName = "localhost" // 服务器名称
        server.serverPort = port    //端口
        server.documentRoot = root // 根目录
        server.setResponseFilters([(Filter404(), .high)])      //404过滤
    }
    
    
   open func startServer() {
    do {
        print("启动HTTP服务器")
        try server.start()
    } catch PerfectError.networkError(let err, let msg) {
        print("网络出现错误:\(err) \(msg)")
    } catch {
        print("网络未知错误")
    }
}
    
    /// 注册路由
    ///
    /// - Parameters:
    ///   - routes: 路由
    ///   - method: 请求方法
    //  inout : 闭包中改变局部变量的值
    func configure(routes: inout Routes, method: HTTPMethod) {
        routes.add(method: .get, uri: "/selectUserInfor") { (request, response) in
            print("\(request.path)")
              let queryParams = request.queryParams
                let jsonDic = ["hello": "world","name": "赵师顺"];
                let json = self.baseResponseBodyJSONData(code: 200, message: "请求成功", data: jsonDic)
                response.setBody(string: json)
                response.completed()
            
        }
    }
    // 处理数据格式
    func baseResponseBodyJSONData(code: Int, message: String, data: Any!) -> String {
        var resoult = Dictionary()
        resoult.updateValue(code, forKey: "code")
        resoult.updateValue(message, forKey: "msg")
        if data != nil {
            resoult.updateValue(data, forKey: "data")
        }
        guard let jsonString = try? resoult.jsonEncodedString() else { return "" }
        return jsonString
    }
    
    /// 404 过滤
    struct Filter404: HTTPResponseFilter {
        func filterHeaders(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
            callback(.continue)
        }
        
        func filterBody(response: HTTPResponse, callback: (HTTPResponseFilterResult) -> ()) {
            if case .notFound = response.status {
                response.setBody(string: "404 文件\(response.request.path)不存在。")
                response.setHeader(.contentLength, value: "\(response.bodyBytes.count)")
                callback(.done)
                response.completed()
            } else {
                callback(.continue)
                response.completed()
            }
        }
    }
}

根据参数,配置路由

打开main.swift 文件 引入import PerfectHTTPServer


import PerfectHTTP
import PerfectHTTPServer
// 配置路由
let netWorkServer = NetworkServerManager.init(root: "webroot", port: 8080, routesArray: [["method":"GET","url":"/api"]])
// 启动服务器
netWorkServer.startServer()

运行后 控制器打印数据,表示本地服务启动

启动HTTP服务器
[INFO] Starting HTTP server localhost on 0.0.0.0:8080
/api/selectUserInfor

请求接口,获取数据

Perfect 网络篇_第1张图片
屏幕快照 2019-07-05 下午5.16.36.png

你可能感兴趣的:(Perfect 网络篇)