API实现目标
- /api/ GET
获取资源目录
films资源
/api/films/?page={id} GET
/api/films/pages GET
/api/films/{id} GET
people资源
/api/people/?page={id} GET
/api/people/pages GET
/api/people/{id} GET
planets资源
/api/planets/?page={id} GET
/api/planets/pages GET
/api/planets/{id} GET
species资源
/api/species/?page={id} GET
/api/species/pages GET
/api/species/{id} GET
starships资源
/api/starships/?page={id} GET
/api/starships/pages GET
/api/starships/{id} GET
vehicles资源
/api/vehicles/?page={id} GET
/api/vehicles/pages GET
/api/vehicles/{id} GET - /register POST
注册用户 - /login POST
用户登录
代码实现
代码仓库:https://github.com/BigBrother3/server
路由结构:
mx.Handle("/api/", negroni.New(
negroni.HandlerFunc(models.ValidateMid),
negroni.HandlerFunc(apiHandler(formatter)),
))
mx.HandleFunc("/login", loginHandler).Methods("POST")
mx.HandleFunc("/register", registerHandler).Methods("POST")
mx.HandleFunc("/api/films/", filmsHandler(formatter)).Methods("GET")
mx.HandleFunc("/api/films/pages", filmsPagesHandler).Methods("GET")
filmsSubRouter := mx.PathPrefix("/api/films").Subrouter()
filmsSubRouter.HandleFunc("/{id:[0-9]+}", getFilmsById).Methods("GET")
mx.HandleFunc("/api/people/", peopleHandler(formatter)).Methods("GET")
mx.HandleFunc("/api/people/pages", peoplePagesHandler).Methods("GET")
peopleSubRouter := mx.PathPrefix("/api/people").Subrouter()
peopleSubRouter.HandleFunc("/{id:[0-9]+}", getPeopleById).Methods("GET")
mx.HandleFunc("/api/planets/", planetsHandler(formatter)).Methods("GET")
mx.HandleFunc("/api/planets/pages", planetsPagesHandler).Methods("GET")
planetsSubRouter := mx.PathPrefix("/api/planets").Subrouter()
planetsSubRouter.HandleFunc("/{id:[0-9]+}", getPlanetsById).Methods("GET")
mx.HandleFunc("/api/species/", speciesHandler(formatter)).Methods("GET")
mx.HandleFunc("/api/species/pages", speciesPagesHandler).Methods("GET")
speciesSubRouter := mx.PathPrefix("/api/species").Subrouter()
speciesSubRouter.HandleFunc("/{id:[0-9]+}", getSpeciesById).Methods("GET")
mx.HandleFunc("/api/starships/", starshipsHandler(formatter)).Methods("GET")
mx.HandleFunc("/api/starships/pages", starshipsPagesHandler).Methods("GET")
starshipsSubRouter := mx.PathPrefix("/api/starships").Subrouter()
starshipsSubRouter.HandleFunc("/{id:[0-9]+}", getStarshipsById).Methods("GET")
mx.HandleFunc("/api/vehicles/", vehiclesHandler(formatter)).Methods("GET")
mx.HandleFunc("/api/vehicles/pages", vehiclesPagesHandler).Methods("GET")
vehiclesSubRouter := mx.PathPrefix("/api/vehicles").Subrouter()
vehiclesSubRouter.HandleFunc("/{id:[0-9]+}", getVehiclesById).Methods("GET")
使用curl进行mock测试
- 资源访问(以films为例子)
访问固定ID的film
访问分页(分页长度为5)
获取总页数
- 注册登陆实现授权访问
注册用户
未登录前访问受限资源
用户登录
访问受限资源