Skip to content

Commit 1ee43fd

Browse files
author
Vic Shóstak
committed
Add new helper: Getenv
1 parent 27bfe61 commit 1ee43fd

File tree

2 files changed

+45
-0
lines changed

2 files changed

+45
-0
lines changed

README.md

Lines changed: 19 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -10,6 +10,24 @@ A most useful helpers for build the best **Go** web applications with
1010

1111
## 📖 List of helpers
1212

13+
### `gowebly.Getenv`
14+
15+
Helper to get the given environment variable. If key is not found, sets a
16+
fallback value.
17+
18+
```go
19+
import (
20+
"github.com/gowebly/helpers"
21+
)
22+
23+
// Get a value of the environment variable 'BACKEND_PORT'
24+
// or sets it to a fallback value '5000'.
25+
gowebly.Getenv("BACKEND_PORT", "5000")
26+
```
27+
28+
> 💡 Note: This is a more advanced version of the built-in
29+
> [os.Getenv][go_os_getenv_url] function.
30+
1331
### `gowebly.ParseTemplates`
1432

1533
Helper to parse list of the given templates to the HTTP handler.
@@ -80,6 +98,7 @@ under the [Apache 2.0 License][repo_license_url], created and supported by
8098
[go_version_img]: https://img.shields.io/badge/Go-1.21+-00ADD8?style=for-the-badge&logo=go
8199
[go_code_coverage_img]: https://img.shields.io/badge/code_coverage-0%25-success?style=for-the-badge&logo=none
82100
[go_report_img]: https://img.shields.io/badge/Go_report-A+-success?style=for-the-badge&logo=none
101+
[go_os_getenv_url]: https://pkg.go.dev/os#Getenv
83102

84103
<!-- Repository links -->
85104

getenv.go

Lines changed: 26 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,26 @@
1+
package gowebly
2+
3+
import (
4+
"os"
5+
)
6+
7+
// Getenv gets the given environment variable. This is a more advanced version
8+
// of the built-in os.Getenv function.
9+
//
10+
// If key is not found, Getenv sets it to a fallback value.
11+
//
12+
// Example:
13+
//
14+
// import (
15+
// "github.com/gowebly/helpers"
16+
// )
17+
//
18+
// // Get a value of the environment variable 'BACKEND_PORT' or sets it to a fallback value '5000'.
19+
// gowebly.Getenv("BACKEND_PORT", "5000")
20+
func Getenv(key, fallback string) string {
21+
if value, ok := os.LookupEnv(key); ok {
22+
return value
23+
}
24+
25+
return fallback
26+
}

0 commit comments

Comments
 (0)