create a vapor http server in swift

To create a Vapor HTTP server in Swift, follow these steps:

  1. Install Vapor by running the following command in Terminal:
brew install vapor
19 chars
2 lines
  1. Create a new Vapor project by running the following command in Terminal:
vapor new MyServer
19 chars
2 lines
  1. Change directory into your project folder:
cd MyServer
12 chars
2 lines
  1. Open the project in Xcode:
open Package.swift
19 chars
2 lines
  1. In your Package.swift file, add the Vapor dependency to your project:
main.swift
// swift-tools-version:5.2
import PackageDescription
let package = Package(
    name: "MyServer",
    dependencies: [
        .package(url: "https://github.com/vapor/vapor.git", from: "4.0.0")
    ],
    targets: [
        .target(name: "MyServer", dependencies: [
            .product(name: "Vapor", package: "vapor")
        ])
    ]
)
338 chars
14 lines
  1. Run the following command in Terminal to regenerate your project using the updated Package.swift file:
vapor update
13 chars
2 lines
  1. In your Xcode project, open the Sources/App/main.swift file. This is where you will write your Swift code to create the HTTP server.

  2. In the main.swift file, add the following code to create a new Vapor.Application object:

main.swift
import Vapor
let app = Application()
37 chars
3 lines
  1. Add a new HTTP GET route to your server that returns a response to the client:
main.swift
app.get { req in
    return "Hello, world!"
}
46 chars
4 lines
  1. Start your server by calling the app.run() method:
main.swift
app.run()
10 chars
2 lines
  1. Run your server by pressing the play button in Xcode or by running the following command in Terminal:
vapor run
10 chars
2 lines

Congratulations, you've created a Vapor HTTP server in Swift!

gistlibby LogSnag