New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Possible issues around file encoding #66
Comments
Could you provide example .env files? |
Unfortunately I do not have these issues myself. I only got reports without actual example files. But there is at least that in the linked issue:
to create the |
It works for me. PowerShell/echo created the file in UTF-8 on my system. use dotenvy::dotenv;
use std::{env, error::Error};
fn main() -> Result<(), Box<dyn Error>> {
dotenv()?;
println!("DATABASE_URL: {}", env::var("DATABASE_URL")?);
Ok(())
} |
|
Using my earlier example, you would get this error:
If you do need to handle .env files that may or may not be UTF-8 encoded, the encoding_rs_io crate is useful. The following example works with your provided file: use encoding_rs_io::DecodeReaderBytes;
use std::{
env, error, fs,
io::{self, Read},
};
const DOTENV_FILE: &str = "env.txt";
fn main() -> Result<(), Box<dyn error::Error>> {
if let Err(e) = dotenvy::from_path(DOTENV_FILE) {
match e {
dotenvy::Error::Io(io_err) => match io_err.kind() {
io::ErrorKind::InvalidData => {
// This is the error when the stream doesn't contain valid UTF-8
let bytes = fs::read(DOTENV_FILE)?;
let mut decoder = DecodeReaderBytes::new(&bytes[..]);
let mut dest = Vec::new();
// Must read to end to ensure that the stream is fully decoded
decoder.read_to_end(&mut dest)?;
dotenvy::from_read(&dest[..])?;
}
_ => return Err(io_err.into()),
},
_ => return Err(e.into()),
}
}
println!("DATABASE_URL: {}", env::var("DATABASE_URL")?);
Ok(())
} Supporting additional encodings is out of scope for this small crate, but I can add this example to this repo to help future users. Hope this helps! |
Adding an example sounds like a great idea 👍 |
This is mostly a second hand report. We got an issue report at the diesel repo about issues where the
.env
file uses a different encoding that UTF-8. See here for the original report.Not sure if that counts a bug in
dotenvy
or if that should be handled at application level.The text was updated successfully, but these errors were encountered: