Currently in Beta - View old docs

Kitura Server Style Guide

This guide covers a way of structuring your project code to make future development easier and keep your project files looking clean.

Prerequisites

  • Kitura Server: Learn how to create one in our Getting Started guide.

Recommended Project Structure

We recommend you follow the Model-View-Controller (MVC) design pattern for your Kitura project (with controllers in our case called routes). An example file structure for a project following this patten is:

    MyKituraApp
    ├── Package.swift
    ├── Sources
    │    ├── MyKituraApp
    │    │    └── main.swift
    │    └── Application
    │         ├── Application.swift
    │         ├── Routes
    │         │    └── HealthRoutes.swift
    │         ├── Models
    │         │    └── Book.swift
    │         └── Middlewares
    │              └── CheckoutSession.swift
    ├── Views
    │    └── Template.stencil
    ├── public
    │    └── Img.jpg
    └── Tests
         └── ApplicationTests
    

If you used the Kitura CLI, or Kitura macOS app, to create your project your files will already be in this structure.

This might seem a bit complex, so let's break down what these folders and files are:

  • Package.swift – defines packages that your app depends on and their versions
  • main.swift - the file that is run to initialize your app and run your server
  • Application.swift - the application that glues everything together
  • Routes – (also known as controllers) defines your app routes and their logic
  • Middlewares – Kitura middlewares which process the incoming requests before handing them down to the routes
  • Models – represents data, implements business logic and handles storage
  • public – contains all the static files like images, styles and javascript
  • Views – provides templates which are rendered and served by your routes
  • Tests – contains the Swift tests for your project

Throughout these guides we will assume you have a project set up as described above. If you generated your project with the Kitura macOS app or Kitura CLI, skip ahead to Step 5: Defining a Book model. If you generated your project using the Swift Package Manager (SPM), the following steps will produce the above structure.

Step 1: Create the Application directory

Within our Sources directory we will first create an Application directory:

mkdir Sources/Application

This is the directory where we will store all of our application code. Note, code in the project's main.swift file isn't easy to test because you can't import an executable target as a module, so to encourage the creation of easily testable code we have minimal code in our main.swift file and recommend putting application code into a separate Application directory.

Next we will create our Application.swift file:

touch Sources/Application/Application.swift

Next we need to create our Routes directory:

mkdir Sources/Application/Routes

This is where we will store all of our route handlers.

Next we will rename the directory within Tests to ApplicationTests:

mv Tests/MyKituraAppTests/ Tests/ApplicationTests

Step 2: Update the Package.swift file

Next we need to configure the targets within our Package.swift file to add in Application as a dependency so that we can build our new project structure:

targets: [
    .target(name: "MyKituraApp", dependencies: [ .target(name: "Application"), "Kitura"]),
    .target(name: "Application", dependencies: [ "Kitura" ]),

    .testTarget(name: "ApplicationTests" , dependencies: [.target(name: "Application"), "Kitura" ])
]

Now we can rebuild our project:

swift build

If you are on macOS and would like to work within an Xcode project then you need to regenerate your Xcode project:

swift package generate-xcodeproj

You may need to reopen the Xcode project for these changes to take effect.

Step 3: Add code to the Application.swift file

Earlier, we created the Application.swift file but we didn't add any code to it.

Open the Application.swift file in our default text editor:

open Sources/Application/Application.swift

The Application.swift file will be responsible for starting our Kitura server.

Add the following code to the Application.swift file:

import Kitura

public class App {

    let router = Router()

    public init() throws {

    }

    func postInit() throws {

    }

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

This code creates an instance of Router, which will route incoming requests to the correct endpoints. Within the run() method we register our router instance to run on port 8080. The call to Kitura.run() does not return immediately - it will block until the server is stopped.

The postInit() function is where we configure and set up the router, prior to starting the server.

Step 4: Add code to the main.swift file

Now that we have created our App class in our Application.swift file we can use it within our main.swift file.

Open the main.swift file in your editor:

open Sources/MyKituraApp/main.swift

Replace the existing code with the following:

import Application

do {
    let app = try App()
    try app.run()

} catch let error {
    print(error.localizedDescription)
}

This code will create an App instance and run it.

Step 5: Defining a Book model

As we are simulating a bookstore in our guides, we are going to need to define a book. The book is a model so the first thing we need to do is create our Models folder:

mkdir Sources/Application/Models

This is the directory where we will store all of our models.

Next we will create our Book.swift file:

touch Sources/Application/Models/Book.swift

We will open the Book.swift file in our default text editor:

open Sources/Application/Models/Book.swift

Inside this file we define our Book:

struct Book: Codable {
    let id: Int
    let title: String
    let price: Double
    let genre: String

    init(id: Int, title: String, price: Double, genre: String) {
        self.id = id
        self.title = title
        self.price = price
        self.genre = genre
    }
}
Back to top