mappings.go 1.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869
  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}/update": "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. joinedPath := path.Join("/", name, p)
  31. if strings.HasSuffix(p, "/") {
  32. joinedPath += "/"
  33. }
  34. fns[joinedPath] = method.Interface().(func(map[string]string, *http.Request) (interface{}, error))
  35. }
  36. }
  37. return nil
  38. }
  39. func GetFunc(path string) (GetFn, error) {
  40. fn, ok := fns[path]
  41. if !ok {
  42. return nil, fmt.Errorf("Can't map path %s to any model methods.", path)
  43. }
  44. return fn, nil
  45. }
  46. func GetNothing(args map[string]string) (interface{}, error) {
  47. return nil, nil
  48. }
  49. func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
  50. return nil, nil
  51. }
  52. func modelName(s interface{}) string {
  53. if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
  54. return t.Elem().Name()
  55. } else {
  56. return t.Name()
  57. }
  58. }