Skip to content

Instantly share code, notes, and snippets.

@vzsg
Last active September 19, 2019 08:47
Show Gist options
  • Select an option

  • Save vzsg/ef79aebcd4716afc71c9c231c1ee0cbe to your computer and use it in GitHub Desktop.

Select an option

Save vzsg/ef79aebcd4716afc71c9c231c1ee0cbe to your computer and use it in GitHub Desktop.
Simple .env file injector for Vapor 3
import Foundation
import Service
#if os(Linux)
import Glibc
#else
import Darwin
#endif
extension Environment {
func injectEnvFile(_ path: String) {
guard let data = FileManager.default.contents(atPath: path), let string = String(data: data, encoding: .utf8) else {
return
}
string.components(separatedBy: "\n")
.map { $0.trimmingCharacters(in: CharacterSet.whitespacesAndNewlines) }
.compactMap { (line: String) -> (String, String)? in
guard let equalsIndex = line.index(of: "=") else {
return nil
}
let key = String(line.prefix(through: line.index(before: equalsIndex)))
let value = String(line.suffix(from: line.index(after: equalsIndex)))
return (key, value)
}
.forEach {
setenv($0.0, $0.1, 1)
}
}
}
DATABASE_URL=postgres://blablabla:password@server:5432/test
import Vapor
import Leaf
public func configure(_ config: inout Config, _ env: inout Environment, _ services: inout Services) throws {
env.injectEnvFile(DirectoryConfig.detect().workDir + ".env")
// Environment, ProcessInfo, etc. all see the overridden value
let databaseURL = Environment.get("DATABASE_URL") ?? "..."
// ... registering providers, services, etc. truncated ...
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment