Skip to content

Latest commit

 

History

History
executable file
·
150 lines (114 loc) · 3.43 KB

gettingstarted.md

File metadata and controls

executable file
·
150 lines (114 loc) · 3.43 KB
layout title menu lang redirect_from
page
Kitura "Hello World" example
starter
en
/starter/helloworld.html

Getting Started

Let's develop your first Kitura web application!

First, create a new project directory:

$ mkdir myFirstProject

Next, create a new Swift project using the Swift Package Manager.

$ cd myFirstProject
$ swift package init --type executable

Now your directory structure under myFirstProject should look like this:

myFirstProject
├── Package.swift
├── Sources
│   └── main.swift
└── Tests

info For more information on the Swift Package Manager, visit swift.org.


In Package.swift, add Kitura as a dependency for your project.

import PackageDescription

let package = Package(
    name: "myFirstProject",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 2)
    ])

In Sources/main.swift, add the following code.

import Kitura

// Create a new router
let router = Router()

// Handle HTTP GET requests to /
router.get("/") {
    request, response, next in
    response.send("Hello, World!")
    next()
}

// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: 8090, with: router)

// Start the Kitura runloop (this call never returns)
Kitura.run()

Compile your application:

$ swift build

Now run your new web application:

$ .build/debug/myFirstProject

Open your browser at http://localhost:8090


Add logging (optional)

In the code example above no messages from Kitura will be logged to the console. You may want to add a logger to help diagnose any problems that occur.


Add a HeliumLogger dependency to Package.swift.

import PackageDescription

let package = Package(
    name: "myFirstProject",
    dependencies: [
        .Package(url: "https://github.com/IBM-Swift/Kitura.git", majorVersion: 1, minor: 2),
        .Package(url: "https://github.com/IBM-Swift/HeliumLogger.git", majorVersion: 1, minor: 1)
    ])

Enable HeliumLogger in Sources/main.swift.

import Kitura
import HeliumLogger

// Initialize HeliumLogger
HeliumLogger.use()

// Create a new router
let router = Router()

// Handle HTTP GET requests to /
router.get("/") {
    request, response, next in
    response.send("Hello, World!")
    next()
}

// Add an HTTP server and connect it to the router
Kitura.addHTTPServer(onPort: 8090, with: router)

// Start the Kitura runloop (this call never returns)
Kitura.run()

## Next Steps

Learn how to [Deploy your Application to the Cloud](/{{ page.lang }}/starter/deploying.html).