dtlc84438 2014-12-24 19:18
浏览 61
已采纳

用接口返回类型定义接口方法

TLDR Here is a playground that demonstrates the issue if you try to run it: https://play.golang.org/p/myQtUVg1iq

I am making a REST API and have many types of resources that can be retrieved via a GET request

GET http://localhost/api/users
GET http://localhost/api/groups

I have a models package which abstracts how the different resources are implemented:

func(m *UserManager) Get() []Users {
    // Internal logic, assume returns correct results
}

func(m *GroupManager) Get() []Groups {
    // Internal logic, assume returns correct results
}

A routes file setups all the routes and handlers:

users := models.UserManager{}
groups := models.GroupManager{}

func GetUsersHandler (w http.ResponseWriter, r *http.Request) {
    users := users.Get()
    // Implementation details, writing to w as JSON
}

func GetGroupsHandler (w http.ResponseWriter, r *http.Request) {
    groups := groups.Get()
    // Implementation details, writing to w as JSON
}

func registerRoutes(r *mux.Router) {
    r.handleFunc("/api/users", GetUsersHandler).Method("GET")
    r.handleFunc("/api/groups", GetGroupsHandler).Method("GET")
}

I am trying to make this more generic by creating an interface and then only needing a single GetHandler. Something like this:

type Getter interface {
    Get() []interface{}
}

func GetHandler(g Getter) {
    return func(w http.ResponseWriter, r *http.Request) {
        results := g.Get()
        // Implementation details, writing to w as JSON
    }
}

func registerRoutes(r *mux.Router) {
    r.handleFunc("/api/users", GetHandler(&users)).Method("GET")
    r.handleFunc("/api/groups", GetHandler(&groups)).Method("GET")
}

This is really close to working, the only problem is the return type from the models is a specific object type, but the interface just uses the interface return type. Is there any way to solve this without making the models return []interface{}?

https://play.golang.org/p/myQtUVg1iq

  • 写回答

2条回答 默认 最新

  • donglu9978 2015-01-15 15:45
    关注

    I ended up avoiding this problem entirely and instead of trying to reduce the amount of code I am using the new go generate feature in Go 1.4 to create the code that is necessary for each resource.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥15 乌班图ip地址配置及远程SSH
  • ¥15 怎么让点阵屏显示静态爱心,用keiluVision5写出让点阵屏显示静态爱心的代码,越快越好
  • ¥15 PSPICE制作一个加法器
  • ¥15 javaweb项目无法正常跳转
  • ¥15 VMBox虚拟机无法访问
  • ¥15 skd显示找不到头文件
  • ¥15 机器视觉中图片中长度与真实长度的关系
  • ¥15 fastreport table 怎么只让每页的最下面和最顶部有横线
  • ¥15 R语言卸载之后无法重装,显示电脑存在下载某些较大二进制文件行为,怎么办
  • ¥15 java 的protected权限 ,问题在注释里