package orm import ( "fmt" "net/http" "path" "reflect" "strings" "github.com/jinzhu/inflection" ) var ( getFns map[string]func(args map[string]string) (interface{}, error) postFns map[string]func(args map[string]string, r *http.Request) (interface{}, error) ) func init() { getFns = make(map[string]func(args map[string]string) (interface{}, error), 0) } func MapModels(models []interface{}, handlers map[string]string) { for _, model := range models { name := inflection.Plural(strings.ToLower(modelName(model))) for p, action := range map[string]string{ "": "GetAll", "create": "Create", "{id}": "Get", "{id}/udpate": "Update", } { getFns[path.Join("/", name, p)] = reflect.ValueOf(model).MethodByName(action).Interface().(func(map[string]string) (interface{}, error)) } for p, action := range map[string]string{ "{id}/udpate": "Update", } { getFns[path.Join("/", name, p)] = reflect.ValueOf(model).MethodByName(action).Interface().(func(map[string]string) (interface{}, error)) } } } func GetFunc(path string) (GetFn, error) { fn, ok := getFns[path] if !ok { return nil, fmt.Errorf("Can't map path %s to any model methods.", path) } return fn, nil } // // func PostFunc(path string) (PostFn, error) { // // fn, ok := Post[path] // // if !ok { // // return nil, fmt.Errorf("Can't map %s!", path) // // } // // return fn, nil // // } func GetNothing(args map[string]string) (interface{}, error) { return nil, nil } func PostNothing(args map[string]string, r *http.Request) (IDer, error) { return nil, nil } func modelName(s interface{}) string { if t := reflect.TypeOf(s); t.Kind() == reflect.Ptr { return t.Elem().Name() } else { return t.Name() } }