All checks were successful
continuous-integration/drone/push Build is passing
100 lines
2.2 KiB
Go
100 lines
2.2 KiB
Go
package utils
|
|
|
|
import (
|
|
"context"
|
|
"log"
|
|
"log/slog"
|
|
"net"
|
|
"os"
|
|
"path/filepath"
|
|
"strconv"
|
|
"time"
|
|
)
|
|
|
|
const rsaBits = 4096
|
|
|
|
func GetFilePath(path string) string {
|
|
// Check for empty filename
|
|
if len(path) == 0 {
|
|
return ""
|
|
}
|
|
|
|
// check if filename exists
|
|
if _, err := os.Stat(path); os.IsNotExist((err)) {
|
|
if filepath.IsAbs(path) {
|
|
slog.Info("File not found, using absolute path", "filename", path)
|
|
return path
|
|
}
|
|
slog.Info("File not found, searching in same directory as binary", "filename", path)
|
|
// if not, check that it exists in the same directory as the currently executing binary
|
|
ex, err2 := os.Executable()
|
|
if err2 != nil {
|
|
slog.Error("Error determining binary path", "error", err)
|
|
return ""
|
|
}
|
|
binaryPath := filepath.Dir(ex)
|
|
path = filepath.Join(binaryPath, path)
|
|
}
|
|
return path
|
|
}
|
|
|
|
// Get preferred outbound ip of this machine
|
|
// @see https://stackoverflow.com/questions/23558425/how-do-i-get-the-local-ip-address-in-go
|
|
func GetOutboundIP() net.IP {
|
|
conn, err := net.Dial("udp", "8.8.8.8:80")
|
|
if err != nil {
|
|
log.Fatal(err)
|
|
}
|
|
defer conn.Close()
|
|
|
|
localAddr := conn.LocalAddr().(*net.UDPAddr)
|
|
|
|
return localAddr.IP
|
|
}
|
|
|
|
// Check if a file exists from https://stackoverflow.com/questions/12518876/how-to-check-if-a-file-exists-in-go
|
|
func FileExists(filename string) bool {
|
|
info, err := os.Stat(filename)
|
|
if os.IsNotExist(err) {
|
|
return false
|
|
}
|
|
return !info.IsDir()
|
|
}
|
|
|
|
func SleepWithContext(ctx context.Context, d time.Duration) {
|
|
timer := time.NewTimer(d)
|
|
select {
|
|
case <-ctx.Done():
|
|
if !timer.Stop() {
|
|
<-timer.C
|
|
}
|
|
case <-timer.C:
|
|
}
|
|
}
|
|
|
|
// EnvInt parses an environment variable into an int; returns (value, true) when set and valid.
|
|
func EnvInt(key string) (int, bool) {
|
|
val := os.Getenv(key)
|
|
if val == "" {
|
|
return 0, false
|
|
}
|
|
parsed, err := strconv.Atoi(val)
|
|
if err != nil {
|
|
return 0, false
|
|
}
|
|
return parsed, true
|
|
}
|
|
|
|
// DurationFromEnv parses an environment variable representing seconds into a duration, defaulting when unset/invalid.
|
|
func DurationFromEnv(key string, fallback time.Duration) time.Duration {
|
|
val := os.Getenv(key)
|
|
if val == "" {
|
|
return fallback
|
|
}
|
|
seconds, err := strconv.ParseInt(val, 10, 64)
|
|
if err != nil || seconds <= 0 {
|
|
return fallback
|
|
}
|
|
return time.Duration(seconds) * time.Second
|
|
}
|