0

I am trying to create a small program in Swift that should run as a CGI binary with Apache HTTP Server. The binary should load a file and return it to the CGI stdout.

So entering the URL https://example.com/files/image.jpeg (I'm using mod rewrite) for example should load the file located in the /var/www/files/image.jpeg directory.

This is what I have so far (removed some security code to make this smaller):

let requestedFile = "/var/www" + (ProcessInfo.processInfo.environment["REQUEST_URI"] ?? "")

if FileManager.default.fileExists(atPath: requestedFile) {
    /// File found
    print("Status: 200")
    print("Content-Type: image/jpeg") /// Change based on file extension
    print()
    print()
    
    // FIXME: Output file to stdout
    let fileData = try String(contentsOfFile: requestedFile, encoding: .ascii)
    print(fileData)
    
} else {
    /// File does not exist
    print("Status: 404")
    print("Content-Type: text/html")
    print()
    print()
    print("File not found")
}

This does work insofar that a text file gets displayed in the browser as it should, but if the requested file is a binary like an image, the only thing the browser shows is "cannot parse response".

Another problem I encountered with this is, that even for text files the connection interrupts and the first part is transferred only.

Previously I used something like this when I primarily used PHP, I'm pretty new to Swift.

I think a similar solution would be good here, however I have no idea how to read and write binary data from file to stdout (in chunks) without corrupting the data or changing the encoding.

Thanks!

0 Answers0