GoDoxy/internal/common/env.go
2024-10-30 06:25:32 +08:00

71 lines
1.8 KiB
Go

package common
import (
"fmt"
"net"
"os"
"strconv"
"strings"
"github.com/rs/zerolog/log"
)
var (
NoSchemaValidation = GetEnvBool("GOPROXY_NO_SCHEMA_VALIDATION", true)
IsTest = GetEnvBool("GOPROXY_TEST", false) || strings.HasSuffix(os.Args[0], ".test")
IsDebug = GetEnvBool("GOPROXY_DEBUG", IsTest)
IsDebugSkipAuth = GetEnvBool("GOPROXY_DEBUG_SKIP_AUTH", false)
IsTrace = GetEnvBool("GOPROXY_TRACE", false) && IsDebug
ProxyHTTPAddr,
ProxyHTTPHost,
ProxyHTTPPort,
ProxyHTTPURL = GetAddrEnv("GOPROXY_HTTP_ADDR", ":80", "http")
ProxyHTTPSAddr,
ProxyHTTPSHost,
ProxyHTTPSPort,
ProxyHTTPSURL = GetAddrEnv("GOPROXY_HTTPS_ADDR", ":443", "https")
APIHTTPAddr,
APIHTTPHost,
APIHTTPPort,
APIHTTPURL = GetAddrEnv("GOPROXY_API_ADDR", "127.0.0.1:8888", "http")
APIJWTSecret = decodeJWTKey(GetEnv("GOPROXY_API_JWT_SECRET", generateJWTKey(32)))
APIUser = GetEnv("GOPROXY_API_USER", "admin")
APIPasswordHash = HashPassword(GetEnv("GOPROXY_API_PASSWORD", "password"))
)
func GetEnvBool(key string, defaultValue bool) bool {
value, ok := os.LookupEnv(key)
if !ok || value == "" {
return defaultValue
}
b, err := strconv.ParseBool(value)
if err != nil {
log.Fatal().Msgf("env %s: invalid boolean value: %s", key, value)
}
return b
}
func GetEnv(key, defaultValue string) string {
value, ok := os.LookupEnv(key)
if !ok || value == "" {
value = defaultValue
}
return value
}
func GetAddrEnv(key, defaultValue, scheme string) (addr, host, port, fullURL string) {
addr = GetEnv(key, defaultValue)
host, port, err := net.SplitHostPort(addr)
if err != nil {
log.Fatal().Msgf("env %s: invalid address: %s", key, addr)
}
if host == "" {
host = "localhost"
}
fullURL = fmt.Sprintf("%s://%s:%s", scheme, host, port)
return
}