Finish the big cleanup
This commit is contained in:
9
utils/htmx.go
Normal file
9
utils/htmx.go
Normal file
@ -0,0 +1,9 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
)
|
||||
|
||||
func HtmxRedirect(w http.ResponseWriter, url string) {
|
||||
w.Header().Add("HX-Redirect", "/")
|
||||
}
|
58
utils/utils.go
Normal file
58
utils/utils.go
Normal file
@ -0,0 +1,58 @@
|
||||
package utils
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"errors"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
)
|
||||
|
||||
func GenerateRandomString(len int) (string, error) {
|
||||
bin := make([]byte, len)
|
||||
_, err := rand.Read(bin)
|
||||
if err != nil {
|
||||
return "", err
|
||||
}
|
||||
return base64.StdEncoding.EncodeToString(bin), nil
|
||||
}
|
||||
|
||||
func ParseNumber(s string) (int64, error) {
|
||||
s = strings.TrimSpace(s)
|
||||
if len(s) == 0 {
|
||||
s = "0"
|
||||
}
|
||||
|
||||
return strconv.ParseInt(s, 10, 64)
|
||||
}
|
||||
|
||||
func ParseDuration(value string) (time.Duration, error) {
|
||||
const nullDuration = time.Duration(0)
|
||||
if len(value) == 0 {
|
||||
return nullDuration, errors.New("Empty duration string")
|
||||
}
|
||||
|
||||
var unit time.Duration
|
||||
switch value[len(value)-1] {
|
||||
case 's':
|
||||
unit = time.Second
|
||||
case 'm':
|
||||
unit = time.Minute
|
||||
case 'h':
|
||||
unit = time.Hour
|
||||
case 'd':
|
||||
unit = time.Duration(24) * time.Hour
|
||||
case 'w':
|
||||
unit = time.Duration(24*7) * time.Hour
|
||||
default:
|
||||
return nullDuration, errors.New("Invalid duration format")
|
||||
}
|
||||
|
||||
amount, err := strconv.ParseInt(value[0:len(value)-1], 10, 64)
|
||||
if err != nil || amount < 0 {
|
||||
return nullDuration, errors.New("Invalid duration value")
|
||||
}
|
||||
|
||||
return time.Duration(amount) * unit, nil
|
||||
}
|
Reference in New Issue
Block a user