github.com/Goboolean/common@v0.0.0-20231130153141-cb54596b217d/pkg/env/init.go (about)

     1  package env
     2  
     3  import (
     4  	"errors"
     5  	"fmt"
     6  	"os"
     7  	"path/filepath"
     8  
     9  	"github.com/joho/godotenv"
    10  	"github.com/fatih/color"
    11  )
    12  
    13  // Just import this package to get all the env variables at the root of the project
    14  // Import this package anonymously as shown below:
    15  // import _ "github.com/Goboolean/common/pkg/env"
    16  
    17  
    18  func init() {
    19  	path, err := filepath.Abs(".")
    20  	if err != nil {
    21  		panic(err)
    22  	}
    23  
    24  	_, err = os.Stat(filepath.Join(path, "go.mod"))
    25  	for ; os.IsNotExist(err); _, err = os.Stat(filepath.Join(path, "go.mod")) {
    26  		path = filepath.Dir(path)
    27  		if path == "/" {
    28  			panic(errRootNotFound)
    29  		}
    30  	}
    31  
    32  	if err := os.Chdir(path); err != nil {
    33  		panic(err)
    34  	}
    35  
    36  	if err := godotenv.Load(); err != nil {
    37  		warn := color.New(color.FgYellow).PrintfFunc()
    38  		warn("WARN")
    39  		fmt.Println("[0000] No .env file found")
    40  	}
    41  }
    42  
    43  var errRootNotFound = errors.New("could not find root directory, be sure to set root of the project as fetch-server")