htmlcssswiftxcodeperfect

Location of webroot (for css file) in Perfect app


I've cloned the PerfectTemplate project and am using it to serve up html as follows…

import PerfectHTTP
import PerfectHTTPServer

var routes = Routes()

routes.add(method: .get, uri: "/test") { request, response in
    response.addHeader(.contentType, value: "text/html")
    response.setBody(string: """
        <!DOCTYPE html>
        <html lang="en">
            <head>
                <title>Test!</title>
                <link rel="stylesheet" type="text/css" href="style.css">
            </head>
            <body>
                <div class="Welcome">Hello</div>
            </body>
        </html>
        """)
    response.completed()
}

routes.add(method: .get, 
              uri: "/**", 
          handler: StaticFileHandler(documentRoot: "./webroot", allowResponseFilters: true).handleRequest)

try HTTPServer.launch(name: "localhost", 
                      port: 8181, 
                    routes: routes, 
           responseFilters: [(PerfectHTTPServer.HTTPFilter.contentCompression(data: [:]), HTTPFilterPriority.high)])

I'm compiling and running with Xcode, and http://localhost:8181/test is returning the html as expected.

The problem is the location of the external css file. As far as I can tell this should be in a folder called webroot, but where should that folder be when running locally?

For reference, I'm coming at this as an iOS dev, so my knowledge of web development and server config is limited.


Update

Per a suggestion on the Perfect Slack group, I added the css file to the project folder (the same folder as Package.swift), and set the Working Directory of the scheme $(PROJECT_DIR) - but I’m getting a 404 trying to load http://localhost:8181/style.css


Solution

  • With help from the Perfect Slack group, I found a solution. The missing piece for me was the webroot folder. I'd assumed this was some kind of alias, but it turns out that you do need to create an actual folder called webroot. So…

    1. Set the Working Directory of the scheme to $(PROJECT_DIR)
    2. In the project folder, create a folder named webroot and add the css file to that folder. It should look like this…

    enter image description here

    I'm sure all the seasoned web devs are laughing at me right now!