重构如下重复代码库的最佳方法是什么?我在 Golang 上查看了几种不同的方法,但无法快速找到有用的东西。我也在go-restfulSwagger 中使用包func (api ApiResource) registerLostLogin(container *restful.Container) { ws := new(restful.WebService) ws. Path("/lostlogin"). Doc("Lost login"). Consumes(restful.MIME_JSON, restful.MIME_XML). Produces(restful.MIME_JSON, restful.MIME_JSON) // you can specify this per route as well ws.Route(ws.POST("").To(api.authenticate). Doc("Performs lost login actions"). Operation("lostlogin"). Reads(LostLogin{})) // from the request container.Add(ws)}func (api ApiResource) registerAccount(container *restful.Container) { ws := new(restful.WebService) ws. Path("/account"). Doc("Account calls"). Consumes(restful.MIME_JSON, restful.MIME_XML). Produces(restful.MIME_JSON, restful.MIME_JSON) // you can specify this per route as well ws.Route(ws.POST("").To(api.authenticate). Doc("Register calls"). Operation("register"). Reads(Account{})) ws.Route(ws.PUT("").To(api.authenticate). Doc("Modify user details"). Operation("modifyUserDetails"). Reads(Account{})) ws.Route(ws.PUT("security").To(api.authenticate). Doc("Modify security question"). Operation("modifySeucirtyQuestion"). Reads(Account{})) ws.Route(ws.PUT("limit").To(api.authenticate). Doc("Modify limit"). Operation("modifyLimit"). Reads(Account{})) ws.Route(ws.PUT("password").To(api.authenticate). Doc("Modify password"). Operation("modifyPassword"). Reads(Account{})) container.Add(ws)}我主要关心的是围绕所有被复制的 ws 的重复。如果我使用 ApiResource 为接收器使用尊重运算符和指针会更好吗?
1 回答
三国纷争
TA贡献1804条经验 获得超7个赞
你当然可以把它们包起来……也许是这样的:
type registration func(container *restful.Container, ws *restul.WebService)
func registerHandlers(handlers ...registration) {
c := restful.NewContainer()
ws := new(restful.WebService)
for _, h := range handlers {
h(c, ws)
}
}
然后调用它,传入你的所有方法:
api := ApiResource{map[string]intapi.OxiResp{}}
registerHandlers(api.registerLostLogin,
api.registerAccount)
然后你只需要WebService在你的方法中接受实例:
func (api ApiResource) registerAccount(container *restful.Container, ws *restful.WebService)
这至少会WebService在方法调用之间重用实例。不过代码有点多。
- 1 回答
- 0 关注
- 200 浏览
添加回答
举报
0/150
提交
取消