doudou6050 2015-04-21 17:41
浏览 260
已采纳

在Golang中处理api版本的惯用方式是什么?

I'm creating a server in Golang intended for a mobile app. I need to be able to support multiple versions of the API for cases were users don't update the app. The main concern with the versioning, is to return data in the correct format for the version of the mobile app.

I've seen that there are three basic ways to do this.
A. One way is by having one route handler on "/", and then allowing that function to parse the url for versioning.
Example:

func main() {
http.HandleFunc("/", routes.ParseFullURI)
}

B. Use a library such as gorilla/mux to handle patterns within the router, but I saw some warnings that this can be too slow.
Example:

  func main() {
            mux.HandleFunc("{version:}/", routes.ParseVersionForHome)
            mux.HandleFunc("{version:}/getData", routes.ParseVersionForGetDAta)
            mux.HandleFunc("{version:}/otherCall", routes.ParseVersionForOtherCall)
            }

C. Have individual urls that don't change, but based on the header, split into different versions. Example:

func main() {
   http.HandleFunc("/", routes.ParseHeaderForVersionForHome)
   http.HandleFunc("/getData", routes.ParseHeaderForVersionForGetData)
   http.HandleFunc("/otherCall", routes.ParseHeaderForVersionForOtherCall)
}

I'm concerned that option 1 will be too messy code wise. I'm concerned that option 2 will be too slow performance wise, and I'm concerned that option 3 will be difficult for the client to handle, or will get confusing since the version isn't clearly labeled.

Which method is the most idiomatic for Golang, and will result in the greatest performance for a mobile app which will be polling often?

  • 写回答

1条回答 默认 最新

  • dty98339 2015-04-21 18:44
    关注

    There are many routing frameworks that allow for grouping, for instance with echo (a very good framework if you want speed)

    package main
    
    import "github.com/labstack/echo"
    
    func ping(c *echo.Context) {
            c.String(200, "pong")
    }
    
    func main() {
            e := echo.New()
    
            v1 := e.Group("/v1")
            v1.Get("/ping", ping)
    
            v2 := e.Group("/v2")
            v2.Get("/ping", ping)
    
            e.Run(":4444")
    }
    

    I think this is quite clean.

    I am sure many other frameworks allow for this. I know for a fact martini does, but that is not an idiomatic framework...

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 r语言神经网络自变量重要性分析
  • ¥15 基于双目测规则物体尺寸
  • ¥15 wegame打不开英雄联盟
  • ¥15 公司的电脑,win10系统自带远程协助,访问家里个人电脑,提示出现内部错误,各种常规的设置都已经尝试,感觉公司对此功能进行了限制(我们是集团公司)
  • ¥15 救!ENVI5.6深度学习初始化模型报错怎么办?
  • ¥30 eclipse开启服务后,网页无法打开
  • ¥30 雷达辐射源信号参考模型
  • ¥15 html+css+js如何实现这样子的效果?
  • ¥15 STM32单片机自主设计
  • ¥15 如何在node.js中或者java中给wav格式的音频编码成sil格式呢