55 lines
1.3 KiB
Go
55 lines
1.3 KiB
Go
package audit
|
|
|
|
import (
|
|
"encoding/base64"
|
|
"encoding/json"
|
|
"errors"
|
|
"strings"
|
|
"time"
|
|
)
|
|
|
|
const maxCursorLength = 512
|
|
|
|
type cursorData struct {
|
|
CreatedAt time.Time `json:"t"`
|
|
ID string `json:"id"`
|
|
}
|
|
|
|
func encodeCursor(createdAt time.Time, id string) string {
|
|
data := cursorData{
|
|
CreatedAt: createdAt,
|
|
ID: id,
|
|
}
|
|
payload, err := json.Marshal(data)
|
|
if err != nil {
|
|
// This should never happen for a simple struct.
|
|
panic("encodeCursor marshal: " + err.Error())
|
|
}
|
|
return base64.RawURLEncoding.EncodeToString(payload)
|
|
}
|
|
|
|
func encodeCursorString(payload string) string {
|
|
return base64.RawURLEncoding.EncodeToString([]byte(payload))
|
|
}
|
|
|
|
func decodeCursor(cursor string) (cursorData, error) {
|
|
if strings.TrimSpace(cursor) == "" {
|
|
return cursorData{}, errors.New("empty cursor")
|
|
}
|
|
if len(cursor) > maxCursorLength {
|
|
return cursorData{}, errors.New("cursor too long")
|
|
}
|
|
payload, err := base64.RawURLEncoding.DecodeString(cursor)
|
|
if err != nil {
|
|
return cursorData{}, errors.New("invalid cursor encoding")
|
|
}
|
|
var data cursorData
|
|
if err := json.Unmarshal(payload, &data); err != nil {
|
|
return cursorData{}, errors.New("invalid cursor payload")
|
|
}
|
|
if data.CreatedAt.IsZero() || data.ID == "" {
|
|
return cursorData{}, errors.New("incomplete cursor data")
|
|
}
|
|
return data, nil
|
|
}
|