mappings.go 1.5 KB

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