golifehk/utils/shortcuts.go

64 lines
1.5 KiB
Go
Raw Normal View History

2022-09-13 13:42:51 +00:00
package utils
import (
"os"
"strconv"
2022-09-16 20:33:47 +00:00
"strings"
2022-09-13 13:42:51 +00:00
)
2022-09-16 20:33:47 +00:00
var MARKDOWN_ESC []string = []string{"_", "*", "[", "]", "(", ")", "~", "`", ">", "#", "+", "-", "=", "|", "{", "}", ".", "!"}
func WriteMDv2Text( sb *strings.Builder, t string ) {
for _, c := range MARKDOWN_ESC {
t = strings.Replace( t, c, "\\" + c, -1 )
}
sb.WriteString( t )
}
2022-09-16 22:42:49 +00:00
func ToPower( t string ) string {
for s, r := range POWER_NUMBERS {
t = strings.ReplaceAll( t, s, r )
}
return t
}
2022-09-13 13:42:51 +00:00
func TryGetEnv[T any]( name string, fallback T ) T {
v := os.Getenv( name )
if v != "" {
switch any( fallback ).(type) {
case uint64:
p, err := strconv.ParseUint( v, 10, 64 )
if err == nil {
return any( uint64( p ) ).(T)
}
case uint32:
p, err := strconv.ParseUint( v, 10, 32 )
if err == nil {
return any( uint32( p ) ).(T)
}
case int:
p, err := strconv.ParseInt( v, 10, 32 )
if err == nil {
return any( int( p ) ).(T)
}
case float64:
p, err := strconv.ParseFloat( v, 64 )
if err == nil {
return any( float64( p ) ).(T)
}
case float32:
p, err := strconv.ParseFloat( v, 32 )
if err == nil {
return any( float32( p ) ).(T)
}
default:
return any( v ).(T)
}
}
return fallback
}