/
utils.go
78 lines (69 loc) · 2.1 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
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
package grapi
import (
"fmt"
"io"
"io/ioutil"
"net/http"
"reflect"
"strings"
log "github.com/Sirupsen/logrus"
"github.com/gedex/inflector"
"github.com/serenize/snaker"
)
//Miscellaneous utility functions
// getReflectedSlicePtr takes a Type such as User, and returns an
// interface containing &MakeSlice([]User, 0, 0).
func getReflectedSlicePtr(sliceType reflect.Type) interface{} {
slice := reflect.MakeSlice(sliceType, 0, 0)
slicePtr := reflect.New(slice.Type())
slicePtr.Elem().Set(slice)
return slicePtr.Interface()
}
// pluralCamelName takes an interface, and returns its type converted
// to camel_case and pluralised. eg. pluralCamelName(ImportantPerson{})
// should return "important_people"
func pluralCamelName(i interface{}) string {
t := fmt.Sprintf("%T", i)
a := strings.Split(t, ".")
t1 := a[len(a)-1]
t2 := snaker.CamelToSnake(t1)
t3 := inflector.Pluralize(t2)
return t3
}
// pluralCamelNameType takes a type, and returns its type converted
// to camel_case and pluralised.
func pluralCamelNameType(typ reflect.Type) string {
t := fmt.Sprintf("%v", typ)
a := strings.Split(t, ".")
t1 := a[len(a)-1]
t2 := snaker.CamelToSnake(t1)
t3 := inflector.Pluralize(t2)
return t3
}
// httpBody returns the uploaded http body. On io failure we just return
// an empty array.
func httpBody(r *http.Request) []byte {
body, err := ioutil.ReadAll(io.LimitReader(r.Body, 1048576))
if err != nil || r.Body.Close() != nil {
log.WithFields(log.Fields{"error": err}).Warn("Can't read request body")
return []byte("")
}
return body
}
// getID takes a structure pointer which should have a field called ID.
// It returns that structures value.
func getID(sp interface{}) (interface{}, error) {
spv := reflect.ValueOf(sp)
if !spv.IsValid() || spv.Kind() != reflect.Ptr {
return nil, fmt.Errorf("getID expected a pointer")
}
sv := spv.Elem()
if sv.Kind() != reflect.Struct {
return nil, fmt.Errorf("getID expected a pointer to a structure")
}
fieldByName := sv.FieldByName("ID")
if !fieldByName.IsValid() {
return nil, fmt.Errorf("Structure does not have an ID")
}
return fieldByName.Interface(), nil
}