go-maymoon/rootdir.go

73 lines
1.5 KiB
Go
Raw Permalink Normal View History

2023-08-15 04:39:31 +00:00
package maymoon
import (
2023-08-15 04:49:25 +00:00
"errors"
2023-08-15 04:39:31 +00:00
"fmt"
"os"
"path/filepath"
)
const (
publicRootDirName string = "public_root"
publicRootEnvName string = "PUBLIC_ROOT"
)
// RootDir returns the "root" directory.
//
// By default, where the "root" directory is depends which user it is running under.
//
// For example, on a Unix or Unix-like system such as Linux, with a user "joeblow" who has a home-directory at
// "/home/joeblow", RootDir might return "/home/joeblow/public_root".
//
// This can be overridden using the "PUBLIC_ROOT" environment variable.
// For example:
//
// PUBLIC_ROOT=/path/to/public_root
//
// Example usage:
//
// rootDir, err := maymoon.RootDir()
// if nil != err {
// return err
// }
//
// fmt.Printf("The maymoon root-dir is at %q \n", rootDir)
2023-08-15 04:51:38 +00:00
//
// One usage for this function is to use the path it returns in HTTPHandler.
// For example:
//
// rootDir, err := maymoon.RootDir()
// if nil != err {
// return err
// }
//
// // ...
//
// var handler http.Handler = maymoon.HTTPHandler(rootDir)
2023-08-15 04:39:31 +00:00
func RootDir() (string, error) {
{
2023-08-15 04:45:46 +00:00
path := os.Getenv(publicRootEnvName)
2023-08-15 04:39:31 +00:00
if "" != path {
/////////////////////// RETURN
return path, nil
}
}
2023-08-15 04:45:46 +00:00
var path string
2023-08-15 04:39:31 +00:00
{
homedir, err := os.UserHomeDir()
if nil != err {
2023-08-15 04:45:46 +00:00
/////////////////////// RETURN
return "", fmt.Errorf("problem getting user home-directory: %w", err)
2023-08-15 04:39:31 +00:00
}
2023-08-15 04:45:46 +00:00
path = filepath.Join(homedir, publicRootDirName)
if "" == path {
/////////////////////// RETURN
return "", errors.New("empty path")
2023-08-15 04:39:31 +00:00
}
}
2023-08-15 04:45:46 +00:00
return path, nil
2023-08-15 04:39:31 +00:00
}