mappings.go 1.4 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768
  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. fns map[string]func(map[string]string, *http.Request) (interface{}, error)
  12. )
  13. func init() {
  14. fns = make(map[string]func(map[string]string, *http.Request) (interface{}, error), 0)
  15. }
  16. func MapHandlers(models []interface{}) error {
  17. for _, model := range models {
  18. name := inflection.Plural(strings.ToLower(modelName(model)))
  19. for p, action := range map[string]string{
  20. "": "ReadAll",
  21. "create": "Create",
  22. "{id}": "Read",
  23. "{id}/udpate": "Update",
  24. "{id}/delete": "Delete",
  25. } {
  26. method := reflect.ValueOf(model).MethodByName(action)
  27. if !method.IsValid() {
  28. return fmt.Errorf("Action %s is not defined for model %s", action, name)
  29. }
  30. fns[path.Join("/", name, p)] = method.Interface().(func(map[string]string, *http.Request) (interface{}, error))
  31. }
  32. }
  33. return nil
  34. }
  35. func GetFunc(path string) (GetFn, error) {
  36. fn, ok := fns[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 GetNothing(args map[string]string) (interface{}, error) {
  43. return nil, nil
  44. }
  45. func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
  46. return nil, nil
  47. }
  48. func modelName(s interface{}) string {
  49. if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
  50. return t.Elem().Name()
  51. } else {
  52. return t.Name()
  53. }
  54. }