-
Notifications
You must be signed in to change notification settings - Fork 2
/
utils.go
56 lines (50 loc) · 1.32 KB
/
utils.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
46
47
48
49
50
51
52
53
54
55
56
package parse
import (
"fmt"
"reflect"
"regexp"
)
// ClassNamer is an interface that allows a type to provide its associated
// Parse.com object class name.
type ClassNamer interface {
ParseClassName() string
}
func objectTypeNameFromSlice(objects interface{}) (string, error) {
rv := reflect.ValueOf(objects)
if rv.Kind() == reflect.Ptr {
rv = rv.Elem()
}
if rv.Kind() != reflect.Slice {
return "", fmt.Errorf("expected slice but got %s", rv.Kind())
}
return objectTypeName(reflect.Zero(rv.Type().Elem()).Interface())
}
func objectTypeName(object interface{}) (string, error) {
if namer, ok := object.(ClassNamer); ok {
return namer.ParseClassName(), nil
}
rv := reflect.ValueOf(object)
var typeName string
switch rv.Kind() {
case reflect.Ptr:
fallthrough
case reflect.Interface:
typeName = rv.Type().Elem().Name()
case reflect.Struct:
typeName = rv.Type().Name()
default:
return "", fmt.Errorf("Expected a pointer or an interface type. Got %s", rv.Kind())
}
return typeName, nil
}
var objectURIRe = regexp.MustCompile("1/classes/(?P<className>[^/]+)(/(?P<objectID>.+))?")
func objectURIToClassAndID(uri string) (className string, objectID string) {
matches := objectURIRe.FindStringSubmatch(uri)
if len(matches) > 1 {
className = matches[1]
}
if len(matches) > 3 {
objectID = matches[3]
}
return
}