forked from mtusi2026/mtusi2026lab2
46 lines
1023 B
Go
46 lines
1023 B
Go
package cursor
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"fmt"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
type Cursor struct {
|
|
Scope string
|
|
CreatedAt time.Time
|
|
ID string
|
|
}
|
|
|
|
func Encode(c Cursor) string {
|
|
raw := fmt.Sprintf("%s|%s|%s", c.Scope, c.CreatedAt.UTC().Format(time.RFC3339Nano), c.ID)
|
|
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
|
}
|
|
|
|
func Decode(s string) (Cursor, error) {
|
|
raw, err := base64.RawURLEncoding.DecodeString(s)
|
|
if err != nil {
|
|
return Cursor{}, fmt.Errorf("malformed cursor encoding")
|
|
}
|
|
parts := strings.SplitN(string(raw), "|", 3)
|
|
if len(parts) != 3 {
|
|
return Cursor{}, fmt.Errorf("malformed cursor structure")
|
|
}
|
|
t, err := time.Parse(time.RFC3339Nano, parts[1])
|
|
if err != nil {
|
|
return Cursor{}, fmt.Errorf("malformed cursor timestamp")
|
|
}
|
|
return Cursor{Scope: parts[0], CreatedAt: t, ID: parts[2]}, nil
|
|
}
|
|
|
|
func IsAfter(createdAt time.Time, id string, c Cursor) bool {
|
|
if createdAt.After(c.CreatedAt) {
|
|
return true
|
|
}
|
|
if createdAt.Equal(c.CreatedAt) {
|
|
return id > c.ID
|
|
}
|
|
return false
|
|
}
|