Skip to content
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

Cookbook "Read an Environment Variable" with the Standard Library #2407

Merged
merged 3 commits into from
Jun 17, 2024
Merged
Changes from 2 commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
23 changes: 23 additions & 0 deletions data/cookbook/read-environment-variable/00-stdlib.ml
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
---
packages: []
---

(*
Both `Sys.getenv` and `Sys.getenv_opt` are functions that take the name of an environment and read its value.

`Sys.getenv` returns the value directly, but raises a `Not_found` exception if the variable doesn't exist.
*)
let path = Sys.getenv "PATH"
let () =
Printf.printf "The path is %s\n" path
sabine marked this conversation as resolved.
Show resolved Hide resolved

(*
In contrast, `Sys.getenv_opt` returns a value of type `string option`: `Some value` if the variable exists and `None` if it doesn't.
*)
let () =
match Sys.getenv_opt "API_KEY" with
| Some p ->
Printf.printf "Ahpi key is %s\n" p
sabine marked this conversation as resolved.
Show resolved Hide resolved
| None ->
print_string "Api key is not set.\n"

Loading