搜尋
首頁後端開發Golanggolang 上基於標頭的版本控制

golang 上基于标头的版本控制

Golang上的基於標頭的版本控制是一種在開發過程中管理程式碼版本的有效方法。透過在程式碼檔案的開頭添加版本信息,開發人員可以輕鬆追蹤程式碼的變更和版本歷史。這種版本控制方法不僅簡單易用,也適用於各種規模的專案。 php小編西瓜將在本文中詳細介紹Golang上基於標頭的版本控制的使用方法和注意事項,幫助開發人員更好地管理和維護程式碼。無論你是初學者還是有經驗的開發者,本文都將為你提供有價值的參考和指導。讓我們一起來探索這個有趣又實用的版本控制技術吧!

問題內容

我想使用 gin 在 go 上實作基於標頭的版本控制。我正在考慮使用中間件功能在路由器上執行此操作。

客戶端將呼叫相同的 api url,並且版本將位於自訂 http 標頭中,如下所示:

呼叫版本1 取得/用戶/12345678 接受版本:v1

呼叫版本 2: 取得/用戶/12345678 接受版本:v2

因此,路由器可以識別標頭並呼叫特定版本。像這樣的事情:

router := gin.Default()

            v1 := router.Group("/v1")
            v1.Use(VersionMiddleware())
            v1.GET("/user/:id", func(c *gin.Context) {
                c.String(http.StatusOK, "This is the v1 API")
            })

            v2 := router.Group("/v2")
            v2.Use(VersionMiddleware())
            v2.GET("/user/:id", func(c *gin.Context) {
                c.String(http.StatusOK, "This is the v2 API")
            })

func VersionMiddleware() gin.HandlerFunc {
    return func(c *gin.Context) {
        version := c.Request.Header.Get(configuration.GetConfigValue("VersionHeader"))

        // Construct the new URL path based on the version number
        path := fmt.Sprintf("/%s%s", version, c.Request.URL.Path)

        // Modify the request URL path to point to the new version-specific endpoint
        c.Request.URL.Path = path
        c.Next()
    }
}

解決方法

請檢查下面的程式碼片段。我使用 reverseproxy 重定向到給定的版本。您需要仔細驗證給定的版本。否則會導致遞歸呼叫。

注意:我使用了兩個版本的/user get/v1/user/v2/user) 。

範例程式碼

package main

import (
 "net/http"
 "net/http/httputil"
 "regexp"

 "github.com/gin-gonic/gin"
)



func main() {
 router := gin.default()
 router.use(versionmiddleware())


 v1 := router.group("/v1")
 v1.get("/user", func(c *gin.context) {
  c.string(http.statusok, "this is the v1 api")
 })

 v2 := router.group("/v2")
 v2.get("/user", func(c *gin.context) {
  c.string(http.statusok, "this is the v2 api")
 })

 router.run(":8082")
}



func versionmiddleware() gin.handlerfunc {
    return func(c *gin.context) {
  
  // you need to check c.request.url.path whether 
  // already have a version or not, if it has a valid
  // version, return.
  regex, _ := regexp.compile("/v[0-9]+")
  ver := regex.matchstring(c.request.url.path)
  if ver {
   return
  }

  version := c.request.header.get("accept-version")
  
  // you need to validate  given version by the user here.
  // if version is not a valid version, return error 
  // mentioning that given version is invalid.

  director := func(req *http.request) {
    r := c.request
    req.url.scheme = "http"
    req.url.host = r.host
    req.url.path =  "/"+ version + r.url.path
    }
  proxy := &httputil.reverseproxy{director: director}
  proxy.servehttp(c.writer, c.request)
 }
}

您可以使用下面的杜松子酒包裝實現。

  • 範例
package main

import (
 "net/http"

 "github.com/gin-gonic/gin"
 "github.com/udayangaac/stackoverflow/golang/75860989/ginwrapper"
)



func main() {
  engine := gin.default()
 router := ginwrapper.newrouter(engine)

 defaultrouter := router.default()
 defaultrouter.get("/profile",func(ctx *gin.context) {

 })

 v1 := router.withversion("/v1")
 v1.get("/user",func(ctx *gin.context) {
  ctx.string(http.statusok, "this is the profile v1 api")
 })

 v2 := router.withversion("/v2")
 v2.get("/user",func(ctx *gin.context) {
  ctx.string(http.statusok, "this is the profile v2 api")
 })

 
 engine.run(":8082")
}
  • 包裝
package ginwrapper

import (
 "fmt"
 "net/http"

 "github.com/gin-gonic/gin"
)

type router struct {
 router *gin.engine
 versiongroups map[string]*gin.routergroup
}

type versionedrouter struct {
 version string
 router
}

func newrouter(router *gin.engine) *router {
 return &router{
  router: router,
  versiongroups: make(map[string]*gin.routergroup),
 }
}

func (a *router) default() versionedrouter {
 return versionedrouter{router: *a }
}

func  (a *router) withversion(version string) versionedrouter {
 if _,ok := a.versiongroups[version]; ok {
  panic("cannot initialize same version multiple times")
 }
 a.versiongroups[version] = a.router.group(version)
 return versionedrouter{router: *a,version:version }
}




func (vr versionedrouter) get(relativepath string, handlers ...gin.handlerfunc)  {
 vr.handle(http.methodget,relativepath,handlers...)
}

// note: you need to follow the same for other http methods.
// as an example, we can write a method for post http method as below,
// 
//  func (vr versionedrouter) post(relativepath string, handlers ...gin.handlerfunc)  {
//   vr.handle(http.methodpost,relativepath,handlers...)
//  }





func (vr versionedrouter)handle(method,relativepath string, handlers ...gin.handlerfunc)  {
 if !vr.isrouteexist(method,relativepath) {
  vr.router.handle(method,relativepath,func(ctx *gin.context) {
   version := ctx.request.header.get("accept-version")
   if len(version) == 0 {
    ctx.string(http.statusbadrequest,"accept-version header is empty")
   }
   ctx.request.url.path = fmt.sprintf("/%s%s", version, ctx.request.url.path)
   vr.router.handlecontext(ctx)
  })
 }

 versionedrelativepath := vr.version + relativepath
 if !vr.isrouteexist(method,versionedrelativepath) {
  vr.router.handle(method,versionedrelativepath,handlers... )
 }
}


func (a versionedrouter) isrouteexist(method,relativepath string) bool {
 for _,route := range a.router.routes() {
  if route.method == method && relativepath == route.path {
   return true
  } 
 }
 return false
}

範例請求

  • /v1/user
#
curl --location 'localhost:8082/user' \
--header 'accept-version: v1'
  • /v2/user
#
curl --location 'localhost:8082/user' \
--header 'Accept-version: v2'

以上是golang 上基於標頭的版本控制的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述
本文轉載於:stackoverflow。如有侵權,請聯絡admin@php.cn刪除
在GO中使用init進行包裝初始化在GO中使用init進行包裝初始化Apr 24, 2025 pm 06:25 PM

在Go中,init函數用於包初始化。 1)init函數在包初始化時自動調用,適用於初始化全局變量、設置連接和加載配置文件。 2)可以有多個init函數,按文件順序執行。 3)使用時需考慮執行順序、測試難度和性能影響。 4)建議減少副作用、使用依賴注入和延遲初始化以優化init函數的使用。

GO的選擇語句:多路復用並發操作GO的選擇語句:多路復用並發操作Apr 24, 2025 pm 05:21 PM

go'SselectStatementTreamLinesConcurrentProgrambyMultiplexingOperations.1)itallowSwaitingOnMultipleChannEloperations,執行thefirstreadyone.2)theDefirstreadyone.2)thedefefcasepreventlocksbysbysbysbysbysbythoplocktrograpraproxrograpraprocrecrecectefnoopeready.3)

GO中的高級並發技術:上下文和候補組GO中的高級並發技術:上下文和候補組Apr 24, 2025 pm 05:09 PM

contextancandwaitgroupsarecrucialingoformanaginggoroutineseflect.1)context contextsallowsAllowsAllowsAllowsAllowsAllingCancellationAndDeadLinesAcrossapibiboundaries,確保GoroutinesCanbestoppedGrace.2)WaitGroupsSynChronizeGoroutines,確保Allimizegoroutines,確保AllizeNizeGoROutines,確保AllimizeGoroutines

使用微服務體系結構的好處使用微服務體系結構的好處Apr 24, 2025 pm 04:29 PM

goisbeneformervicesduetoitssimplicity,效率,androbustConcurrencySupport.1)go'sdesignemphasemphasizessimplicity and效率,Idealformicroservices.2))其ConcconcurnCurnInesSandChannelsOdinesSallessallessallessAlloSalosalOsalOsalOsalOndlingConconcConccompi.3)

Golang vs. Python:利弊Golang vs. Python:利弊Apr 21, 2025 am 12:17 AM

Golangisidealforbuildingscalablesystemsduetoitsefficiencyandconcurrency,whilePythonexcelsinquickscriptinganddataanalysisduetoitssimplicityandvastecosystem.Golang'sdesignencouragesclean,readablecodeanditsgoroutinesenableefficientconcurrentoperations,t

Golang和C:並發與原始速度Golang和C:並發與原始速度Apr 21, 2025 am 12:16 AM

Golang在並發性上優於C ,而C 在原始速度上優於Golang。 1)Golang通過goroutine和channel實現高效並發,適合處理大量並發任務。 2)C 通過編譯器優化和標準庫,提供接近硬件的高性能,適合需要極致優化的應用。

為什麼要使用Golang?解釋的好處和優勢為什麼要使用Golang?解釋的好處和優勢Apr 21, 2025 am 12:15 AM

選擇Golang的原因包括:1)高並發性能,2)靜態類型系統,3)垃圾回收機制,4)豐富的標準庫和生態系統,這些特性使其成為開發高效、可靠軟件的理想選擇。

Golang vs.C:性能和速度比較Golang vs.C:性能和速度比較Apr 21, 2025 am 12:13 AM

Golang適合快速開發和並發場景,C 適用於需要極致性能和低級控制的場景。 1)Golang通過垃圾回收和並發機制提升性能,適合高並發Web服務開發。 2)C 通過手動內存管理和編譯器優化達到極致性能,適用於嵌入式系統開發。

See all articles

熱AI工具

Undresser.AI Undress

Undresser.AI Undress

人工智慧驅動的應用程序,用於創建逼真的裸體照片

AI Clothes Remover

AI Clothes Remover

用於從照片中去除衣服的線上人工智慧工具。

Undress AI Tool

Undress AI Tool

免費脫衣圖片

Clothoff.io

Clothoff.io

AI脫衣器

Video Face Swap

Video Face Swap

使用我們完全免費的人工智慧換臉工具,輕鬆在任何影片中換臉!

熱工具

ZendStudio 13.5.1 Mac

ZendStudio 13.5.1 Mac

強大的PHP整合開發環境

Dreamweaver Mac版

Dreamweaver Mac版

視覺化網頁開發工具

VSCode Windows 64位元 下載

VSCode Windows 64位元 下載

微軟推出的免費、功能強大的一款IDE編輯器

Atom編輯器mac版下載

Atom編輯器mac版下載

最受歡迎的的開源編輯器

SecLists

SecLists

SecLists是最終安全測試人員的伙伴。它是一個包含各種類型清單的集合,這些清單在安全評估過程中經常使用,而且都在一個地方。 SecLists透過方便地提供安全測試人員可能需要的所有列表,幫助提高安全測試的效率和生產力。清單類型包括使用者名稱、密碼、URL、模糊測試有效載荷、敏感資料模式、Web shell等等。測試人員只需將此儲存庫拉到新的測試機上,他就可以存取所需的每種類型的清單。