forked from Oskang09/goloquent
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcursor.go
45 lines (40 loc) · 864 Bytes
/
cursor.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
package goloquent
import (
"encoding/base64"
"encoding/json"
"fmt"
"strings"
"cloud.google.com/go/datastore"
)
// Cursor :
type Cursor struct {
cc []byte
Signature string `json:"signature"`
Key *datastore.Key `json:"next"`
}
// String :
func (c Cursor) String() string {
if c.cc == nil {
return ""
}
return strings.TrimRight(base64.URLEncoding.EncodeToString(c.cc), "=")
}
// DecodeCursor :
func DecodeCursor(c string) (Cursor, error) {
if c == "" {
return Cursor{}, nil
}
if n := len(c) % 4; n != 0 {
c += strings.Repeat("=", 4-n)
}
b, err := base64.URLEncoding.DecodeString(c)
if err != nil {
return Cursor{}, fmt.Errorf("goloquent: invalid cursor")
}
cc := new(Cursor)
cc.cc = b
if err := json.Unmarshal(b, cc); err != nil {
return Cursor{}, fmt.Errorf("goloquent: invalid cursor")
}
return *cc, nil
}