organize project

took me a bit to figure out how to do this properly, but i believe it's improved my understanding of how go works
This commit is contained in:
2026-11-21 16:18:30 -05:00
parent 741b91b637
commit e5a2f47f47
28 changed files with 304 additions and 1148 deletions
+78
View File
@@ -0,0 +1,78 @@
package config
import (
"fmt"
"regexp"
"slices"
"strconv"
"strings"
"time"
)
type Expiry struct {
Label string
Amount int
Unit string
}
// this will parse something like "1d" into 2 groups: the amount, and the unit
var expiryPattern = regexp.MustCompile(`^([1-9][0-9]*)(h|d|w|mo|y)$`)
func ParseExpiry(expiry string) (Expiry, error) {
expiry = strings.TrimSpace(expiry)
if expiry == "0" {
return Expiry{
Label: "indefinite",
Unit: "indefinite",
}, nil
}
matches := expiryPattern.FindStringSubmatch(expiry)
if matches == nil {
return Expiry{}, fmt.Errorf("invalid expiry %q", expiry)
}
// parses the string amount to an int
// the amount is 2nd (1) in the index because the first (0) is the entire string
amount, err := strconv.Atoi(matches[1])
if err != nil {
return Expiry{}, fmt.Errorf("invalid expiry %q: %w", expiry, err)
}
return Expiry{
Label: expiry,
Amount: amount,
Unit: matches[2],
}, nil
}
func FindExpiry(expiries []Expiry, label string) (Expiry, bool) {
index := slices.IndexFunc(expiries, func(expiry Expiry) bool {
return expiry.Label == label
})
if index == -1 {
return Expiry{}, false
}
return expiries[index], true
}
func (expiry Expiry) ExpiresFrom(now time.Time) (*time.Time, error) {
var expires time.Time
switch expiry.Unit {
case "h":
expires = now.Add(time.Duration(expiry.Amount) * time.Hour)
case "d":
expires = now.AddDate(0, 0, expiry.Amount)
case "w":
expires = now.AddDate(0, 0, expiry.Amount*7)
case "mo":
expires = now.AddDate(0, expiry.Amount, 0)
case "y":
expires = now.AddDate(expiry.Amount, 0, 0)
case "indefinite":
return nil, nil
default:
return nil, fmt.Errorf("unsupported expiry unit %q", expiry.Unit)
}
return &expires, nil
}