Last active
September 19, 2019 08:47
-
-
Save vzsg/ef79aebcd4716afc71c9c231c1ee0cbe to your computer and use it in GitHub Desktop.
Simple .env file injector for Vapor 3
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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) | |
| } | |
| } | |
| } |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| DATABASE_URL=postgres://blablabla:password@server:5432/test |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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