Files
rock1hu-bot/local/utl/common/common.go
Fran Jurmanović 14a689ad76 init
2024-09-30 22:00:15 +02:00

100 lines
1.9 KiB
Go

package common
import (
"fmt"
"log"
"net"
"os"
"os/exec"
"regexp"
"strings"
"github.com/gofiber/fiber/v2"
)
type RouteGroups struct {
Concert fiber.Router
}
func CheckError(err error) {
if err != nil {
log.Printf("Error occured. %v", err)
}
}
var matchFirstCap = regexp.MustCompile("(.)([A-Z][a-z]+)")
var matchAllCap = regexp.MustCompile("([a-z0-9])([A-Z])")
func GetMonthFromLocalized(month string) (int, error) {
switch month {
case "január":
return 1, nil
case "február":
return 2, nil
case "március":
return 3, nil
case "április":
return 4, nil
case "május":
return 5, nil
case "június":
return 6, nil
case "július":
return 7, nil
case "augusztus":
return 8, nil
case "szeptember":
return 9, nil
case "október":
return 10, nil
case "november":
return 11, nil
case "december":
return 12, nil
default:
return 0, fmt.Errorf("Month not recognized %1", month)
}
}
func ToSnakeCase(str string) string {
snake := matchFirstCap.ReplaceAllString(str, "${1}_${2}")
snake = matchAllCap.ReplaceAllString(snake, "${1}_${2}")
return strings.ToLower(snake)
}
func GetIP() string {
addrs, err := net.InterfaceAddrs()
if err != nil {
os.Stderr.WriteString("Oops: " + err.Error() + "\n")
os.Exit(1)
}
for _, a := range addrs {
if ipnet, ok := a.(*net.IPNet); ok && !ipnet.IP.IsLoopback() {
if ipnet.IP.To4() != nil {
return ipnet.IP.String()
}
}
}
return ""
}
func Find[T any](lst *[]T, callback func(item *T) bool) *T {
for _, item := range *lst {
if callback(&item) {
return &item
}
}
return nil
}
func RunElevatedCommand(command string, service string) (string, error) {
cmd := exec.Command("powershell", "-nologo", "-noprofile", "-File", "run_sc.ps1", command, service)
output, err := cmd.CombinedOutput()
if err != nil {
log.Panic("error: %v, output: %s", err, string(output))
return "", fmt.Errorf("error: %v, output: %s", err, string(output))
}
return string(output), nil
}