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 做个有关计算的小程序
  • ¥15 MPI读取tif文件无法正常给各进程分配路径
  • ¥15 如何用MATLAB实现以下三个公式(有相互嵌套)
  • ¥30 关于#算法#的问题:运用EViews第九版本进行一系列计量经济学的时间数列数据回归分析预测问题 求各位帮我解答一下
  • ¥15 setInterval 页面闪烁,怎么解决
  • ¥15 如何让企业微信机器人实现消息汇总整合
  • ¥50 关于#ui#的问题:做yolov8的ui界面出现的问题
  • ¥15 如何用Python爬取各高校教师公开的教育和工作经历
  • ¥15 TLE9879QXA40 电机驱动
  • ¥20 对于工程问题的非线性数学模型进行线性化