mappings.go 1.4 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  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. )
  13. func init() {
  14. getFns = make(map[string]func(args map[string]string) (interface{}, error), 0)
  15. }
  16. func MapModels(models []interface{}, handlers map[string]string) {
  17. for _, model := range models {
  18. name := inflection.Plural(strings.ToLower(modelName(model)))
  19. for p, action := range map[string]string{
  20. "": "GetAll",
  21. "create": "Create",
  22. "{id}": "Get",
  23. "{id}/udpate": "Update",
  24. } {
  25. getFns[path.Join("/", name, p)] = reflect.ValueOf(model).MethodByName(action).Interface().(func(map[string]string) (interface{}, error))
  26. }
  27. }
  28. }
  29. func GetFunc(path string) (GetFn, error) {
  30. fn, ok := getFns[path]
  31. if !ok {
  32. return nil, fmt.Errorf("Can't map path %s to any model methods.", path)
  33. }
  34. return fn, nil
  35. }
  36. // // func PostFunc(path string) (PostFn, error) {
  37. // // fn, ok := Post[path]
  38. // // if !ok {
  39. // // return nil, fmt.Errorf("Can't map %s!", path)
  40. // // }
  41. // // return fn, nil
  42. // // }
  43. func GetNothing(args map[string]string) (interface{}, error) {
  44. return nil, nil
  45. }
  46. func PostNothing(args map[string]string, r *http.Request) (IDer, error) {
  47. return nil, nil
  48. }
  49. func modelName(s interface{}) string {
  50. if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr {
  51. return t.Elem().Name()
  52. } else {
  53. return t.Name()
  54. }
  55. }