Swift简易Kitura应用本地主机无法运行?

4

第一篇文章!

我是一名学习Swift的学生,正在进行一项相当大的速成课程。上次,我的教授开始教我们如何进行简单的get和post请求,但我仍在赶进度,很明显还没有掌握一些基础知识。

这是我第一次使用Kitura,并且只是第二次编写Swift代码。出现了一个问题,当我使用swift run命令时,我的打印信息会显示,然后突然出现“程序以退出代码:0结束”,而不是在我的8080端口上运行本地主机来验证我的localhost:8080/上的get响应。

有人能帮我弄清楚我没有看到的问题吗?或者我对服务器端Swift和命令行还没有理解?

print("Hello, world from Swift Main!")

import Kitura

//constant router
let router = Router()


//When the router gets a request (contains everything needed to interpret the request), the server will respond with (Hello World or whatever data)
router.get("/") { request, response, next in
    response.send("Hello world from router.get") //response
    next() //either end the route or go on to the next one
}

//What port for the server to run on
Kitura.addHTTPServer(onPort: 8080, with: router)


//Need to add routes before run(), either in different file or on main
Kitura.run()

谢谢!

1个回答

4
您提供的代码是正确的,所以可能是您的项目结构有问题。
为了正确创建项目,您可以按照以下步骤进行:
1. 创建一个新目录,例如jamie.
2. 从该目录运行swift package init --type=executable来创建一个新项目。该项目将根据目录名称命名为jamie.
3. 编辑Sources/jamie/main.swift并添加您的代码。
4. 编辑Package.swift并将以下内容添加到“Jamie”包的依赖项中:
.package(url: "https://github.com/IBM-Swift/Kitura.git", .upToNextMajor(from: "2.5.0")),.
5. 编辑Package.swift并将其作为“jamie”目标的依赖项列表添加:
dependencies: ["Kitura"]), 然后它应该能够正确运行。如果没有,请检查您尝试使用的端口是否已经在使用中。如果您向项目添加记录器,当Kitura无法绑定端口时,Kitura将记录错误消息。要这样做,请按照以下步骤进行:
  1. Edit Package.swift and add the following to the dependencies of the "Jamie" package:
    .package(url: "https://github.com/IBM-Swift/HeliumLogger.git", .upToNextMinor(from: "1.7.1")),.
  2. Edit Package.swift and add the logger to the list of dependencies for the "jamie" target so that it becomes:
    dependencies: ["Kitura", HeliumLogger"]),
  3. Edit Sources/jamie/main.swift and add the following to the top of the file:

    import LoggerAPI
    import HeliumLogger
    
    HeliumLogger.use(LoggerMessageType.info)
    

    If the port is already in use, you'll get a message similar to the following:

[2019-02-17T12:01:40.723Z] [ERROR] [Kitura.swift:139 start()] 监听端口8080时发生错误: 错误代码: -9992(0x-2708), 地址已被占用。使用 server.failed(callback:) 进行处理

如果还没有加入,建议加入 Kitura 的 Slack 组织,网址为 http://slack.kitura.io


1
是的,你说得对!这绝对是我的端口问题。我会立即在那里加入HeliumLogger。非常感谢! :) - Jamie BRANNAN
如果您遇到了上述最后一个错误,请按照此处的前两个命令执行。 - George

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接