hugo-medialog/utils/utils.go

77 lines
1.5 KiB
Go

package utils
import (
"encoding/json"
"fmt"
"os"
"regexp"
"strings"
"unicode"
)
func CreateDirIfNotExists(dir string) error {
if _, err := os.Stat(dir); os.IsNotExist(err) {
return os.MkdirAll(dir, 0755)
}
return nil
}
func Debug(v interface{}, args ...string) {
// utils.Debug(variable)
debug, err := json.MarshalIndent(v, "", " ")
if err != nil {
fmt.Println("Error marshaling JSON:", err)
return
}
// Print a title if there is one
if len(args) > 0 {
fmt.Printf("%s\n", args[0])
}
fmt.Printf("DEBUG:\n%s\n", string(debug))
}
func DebugBody(body []byte) {
// utils.DebugBody(body)
var jsonResponse interface{}
err := json.Unmarshal(body, &jsonResponse)
if err != nil {
fmt.Println("Error unmarshaling JSON:", err)
}
Debug(jsonResponse, "--API RESPONSE--")
}
func Print(v interface{}) {
fmt.Println("%#v", v)
}
func Sep() {
separator := "════════════════════════════════════════════════"
fmt.Println(separator)
}
func Sluggify(s string) string {
slug := strings.ToLower(s)
var b strings.Builder
for _, r := range slug {
if unicode.IsLetter(r) || unicode.IsDigit(r) {
b.WriteRune(r)
} else {
switch r {
case ' ', '-', '_':
b.WriteRune('-')
}
}
}
slug = b.String()
reg := regexp.MustCompile("[^a-z0-9-]+")
slug = reg.ReplaceAllString(slug, "")
slug = strings.ReplaceAll(slug, "--", "-")
slug = strings.Trim(slug, "-")
return slug
}