Setting Up a Kitura Swift Server: A Beginner’s Guide with Swift Package Manager

Swift Package Manager (SPM) comes bundled with Swift, making it a readily available tool for Swift developers. This guide will walk you through the process of creating a Kitura project from the ground up using SPM, perfect for those starting their journey into server-side Swift development.

Step 1: Create Project

To begin, we’ll use the command line interface (CLI) to interact with Swift Package Manager.

If you’re new to using the command line, simply open Terminal on macOS or Linux to get started.

First, let’s create a directory for our project. This directory will house all our project files.

mkdir MyKituraApp && cd MyKituraApp

The name you give to this directory will also serve as the name for your generated Swift project. Choose a descriptive name for your project.

Next, we initialize this directory as a Swift executable project using SPM:

swift package init --type executable

SPM will generate a basic Swift project structure for you. Now, we need to incorporate our project dependencies, specifically Kitura, to enable server-side functionalities.

Step 2: Create the Application Directory

Within the Sources directory, we’ll create an Application directory. This is a best practice to organize your server-side Swift code.

mkdir Sources/Application

This Application directory will be the central location for all of our application-specific code. This separation helps maintainability and testability. While you could put code directly in main.swift, it becomes harder to test because executable targets aren’t easily imported as modules. By placing our application logic in a separate Application directory, we encourage writing cleaner, testable code.

Next, let’s create the main application file, Application.swift, within this new directory:

touch Sources/Application/Application.swift

We also need to create a Routes directory.

mkdir Sources/Application/Routes

This Routes directory will be dedicated to storing all our route handlers – the logic that dictates how our server responds to different web requests. Keeping routes separate improves the organization of your Kitura Swift Server.

Finally, let’s rename the default test directory within the Tests folder to ApplicationTests to align with our application structure:

mv Tests/MyKituraAppTests/ Tests/ApplicationTests

Step 3: Add Kitura to Our Dependencies

To make use of Kitura in our project, we need to declare it as a dependency. This is done by modifying the Package.swift file, which is the manifest file for Swift Package Manager.

Open Package.swift in your preferred text editor. You can usually do this from the command line:

open Package.swift

Within Package.swift, you’ll need to add Kitura to the dependencies array and also to the dependencies of your targets. Modify your Package.swift file to resemble the following structure:

// swift-tools-version:5.5 // Replace with your Swift tools version
import PackageDescription

let package = Package(
    name: "MyKituraApp",
    dependencies: [
        .package(url: "https://github.com/Kitura/Kitura", from: "2.9.0") // Replace with the latest Kitura release
    ],
    targets: [
        .target(
            name: "MyKituraApp",
            dependencies: [
                .target(name: "Application"),
                "Kitura"
            ]),
        .target(
            name: "Application",
            dependencies: [
                "Kitura"
            ]),
        .testTarget(
            name: "ApplicationTests",
            dependencies: [
                .target(name: "Application"),
                "Kitura"
            ]),
    ]
)

Remember to replace "2.9.0" with the actual latest Kitura release version to ensure you’re using the most up-to-date and stable version. Also, adjust swift-tools-version:5.5 to match your Swift tools version.

Step 4: Add Code to the Application.swift File

In Step 2, we created Application.swift, but it’s currently empty. Let’s add the code that will initialize and start our Kitura server.

Open Sources/Application/Application.swift in your text editor:

open Sources/Application/Application.swift

The Application.swift file will be responsible for setting up and launching your Kitura server. Add the following Swift code to Application.swift:

import Kitura

public class App {
    let router = Router()

    public init() throws {
        // Perform any initialization here
    }

    func postInit() throws {
        // Configure routes and middleware after initialization
    }

    public func run() throws {
        try postInit()
        Kitura.addHTTPServer(onPort: 8080, with: router)
        Kitura.run()
    }
}

This code snippet creates an App class, which encapsulates our Kitura server logic. It initializes a Router instance, which is crucial for directing incoming web requests to the appropriate handlers. The run() method is where the server starts. It calls postInit() for route configuration and then uses Kitura.addHTTPServer to bind our router to port 8080. Finally, Kitura.run() starts the server and blocks the current thread, keeping the server running until it’s stopped.

The postInit() function is designed as a place to configure your server’s routes and middleware. This separation makes the initialization process cleaner and more organized.

Step 5: Add Code to the main.swift File

Now that we have defined our App class in Application.swift, we need to use it in our main.swift file to actually start the server when our application runs.

Open Sources/MyKituraApp/main.swift in your editor:

open Sources/MyKituraApp/main.swift

Replace the existing boilerplate code in main.swift with the following:

import Application

do {
    let app = try App()
    try app.run()
} catch let error {
    print(error.localizedDescription)
}

This simple main.swift file is now responsible for creating an instance of our App class and then calling the run() method to start the Kitura server. The do-catch block ensures that any errors during app initialization or running are caught and their descriptions are printed to the console, which is helpful for debugging.

Step 6: Start the Server

With all the code in place, we are ready to launch our Kitura Swift server!

To start the server from the command line, execute the Swift executable using:

swift run

If you prefer to run your project in Xcode, ensure your build target is set to “My Mac” and then simply run the project from within Xcode. You might be prompted by your system to allow the application to accept incoming network connections – grant this permission to allow your server to be accessible.

Once the server is running, navigate your web browser to http://localhost:8080.

You should be greeted by the default Kitura landing page, confirming that your Kitura Swift server is successfully running.

Project Structure

Congratulations! You have successfully created a Kitura project using Swift Package Manager. Your project now has the following well-organized structure:

MyKituraApp
├── Package.swift
└── Sources/
    ├── MyKituraApp/
    │   └── main.swift
    ├── Application/
    │   └── Application.swift
    └── Routes/
└── Tests/
    └── ApplicationTests/

Let’s break down each part of this structure:

  • Package.swift: This file is the Swift Package Manager manifest. It defines your project’s name, its dependencies (like Kitura), and build targets.
  • main.swift: Located in Sources/MyKituraApp/, this is the entry point of your application. It initializes and starts your Kitura server.
  • Application.swift: In Sources/Application/, this file contains the App class, which sets up the Kitura router and configures the server.
  • Routes/: This directory, inside Sources/Application/, is intended for organizing your route handlers, which manage how your server responds to different HTTP requests.
  • ApplicationTests/: Found within Tests/, this directory houses the Swift tests for your application, ensuring the reliability of your server logic.

This project structure, generated using Swift Package Manager, is consistent with the structure often produced by the Kitura command-line interface and will be consistently used throughout further guides and tutorials for building more complex Kitura applications.

Next Steps

Now that you have a basic Kitura Swift server up and running, you can explore more advanced features and functionalities:

Logging: Enhance your server by learning how to implement logging to track application behavior and debug issues effectively.

Routing: Dive deeper into routing concepts and discover the two routing types supported by Kitura to build more sophisticated web applications.

By following these next steps, you can expand your knowledge and build more robust and feature-rich Kitura Swift servers.

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *