mappings.go 1.7 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677
  1. package orm
  2. import (
  3. "fmt"
  4. "net/http"
  5. "path"
  6. "reflect"
  7. "strings"
  8. "github.com/jinzhu/inflection"
  9. )
  10. var (
  11. getFns map[string]func(args map[string]string) (interface{}, error)
  12. postFns map[string]func(args map[string]string, r *http.Request) (interface{}, error)
  13. )
  14. func init() {
  15. getFns = make(map[string]func(args map[string]string) (interface{}, error), 0)
  16. }
  17. func MapModels(models []interface{}, handlers map[string]string) {
  18. for _, model := range models {
  19. name := inflection.Plural(strings.ToLower(modelName(model)))
  20. for p, action := range map[string]string{
  21. "": "GetAll",
  22. "create": "Create",
  23. "{id}": "Get",
  24. "{id}/udpate": "Update",
  25. } {
  26. getFns[path.Join("/", name, p)] = reflect.ValueOf(model).MethodByName(action).Interface().(func(map[string]string) (interface{}, error))
  27. }
  28. for p, action := range map[string]string{
  29. "{id}/udpate": "Update",
  30. } {
  31. getFns[path.Join("/", name, p)] = reflect.ValueOf(model).MethodByName(action).Interface().(func(map[string]string) (interface{}, error))
  32. }
  33. }
  34. }
  35. func GetFunc(path string) (GetFn, error) {
  36. fn, ok := getFns[path]
  37. if !ok {
  38. return nil, fmt.Errorf("Can't map path %s to any model methods.", path)
  39. }
  40. return fn, nil
  41. }
  42. // // func PostFunc(path string) (PostFn, error) {
  43. // // fn, ok := Post[path]
  44. // // if !ok {
  45. // // return nil, fmt.Errorf("Can't map %s!", path)
  46. // // }
  47. // // return fn, nil
  48. // // }
  49. func GetNothing(args map[string]string) (interface{}, error) {
  50. return nil, nil
  51. }
  52. func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
  53. return nil, nil
  54. }
  55. func modelName(s interface{}) string {
  56. if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
  57. return t.Elem().Name()
  58. } else {
  59. return t.Name()
  60. }
  61. }