美文网首页
swift perfect 搭建服务器

swift perfect 搭建服务器

作者: 醉影 | 来源:发表于2019-11-22 14:40 被阅读0次

    1.cd 到要安装的目录下
    2.终端执行
    swift package init --type executable
    会自动创建相关文件

    pro:Perfect2 qzp$ swift package init --type executable
    Creating executable package: Perfect2
    Creating Package.swift
    Creating [README.md](http://README.md)
    Creating .gitignore
    Creating Sources/
    Creating Sources/Perfect2/main.swift
    Creating Tests/
    

    3.打开Package.swift 文件添加相关依赖

    // swift-tools-version:5.0
    // The swift-tools-version declares the minimum version of Swift required to build this package.
    
    import PackageDescription
    
    //swift 编译的最低版本3.0.0
    let package = Package(
        name: "New_Server",
        dependencies: [
            .package(url: "https://github.com/PerfectlySoft/Perfect-HTTPServer.git", from: "3.0.0")
        ],
        targets: [
            // Targets are the basic building blocks of a package. A target can define a module or a test suite.
            // Targets can depend on other targets in this package, and on products in packages which this package depends on.
            .target(
                name: "New_Server",
                dependencies: ["PerfectHTTPServer"]), //添加依赖关系
            .testTarget(
                name: "New_ServerTests",
                dependencies: ["New_Server"]),
        ]
    )
    
    

    4.构建项目
    swift build
    5.创建xcode启动文件
    每次导入之后需要执行
    swift package generate-xcodeproj
    6.改写main.swift

    import PerfectLib
    import PerfectHTTP
    import PerfectHTTPServer
    
    //注册路由
    var routes = Routes();
    routes.add(method: HTTPMethod.get, uri: "/") { (request:HTTPRequest, response:HTTPResponse) in
        response.setHeader(.contentType, value: "text/html");
        response.appendBody(string: "<html><title>Hello, world!</title><body>Hello, world!</body></html>").completed()
    }
    
    let server = HTTPServer();
    server.serverPort = 8090;
    server.documentRoot = "webroot";
    server.addRoutes(routes);
    do{
        try server.start();
    } catch {
        fatalError("\(error)")
    }
    

    相关文章

      网友评论

          本文标题:swift perfect 搭建服务器

          本文链接:https://www.haomeiwen.com/subject/wzqwaqtx.html