iris/_examples/routing/versioning/main.go
Gerasimos (Makis) Maropoulos 7aa2d1f9d5
make versioning.Group a Party compatible by using a type alias on its embedded field
was reported as missing of the a Party method, the type alias is a good hack to solve that
2021-01-05 18:16:32 +02:00

90 lines
2.4 KiB
Go

package main
import (
"github.com/kataras/iris/v12"
"github.com/kataras/iris/v12/versioning"
)
func main() {
app := iris.New()
examplePerRoute(app)
examplePerParty(app)
// Read the README.md before any action.
app.Listen(":8080")
}
// How to test:
// Open Postman
// GET: localhost:8080/api/cats
// Headers[1] = Accept-Version: "1" and repeat with
// Headers[1] = Accept-Version: "2.5"
// or even "Accept": "application/json; version=2.5"
func examplePerRoute(app *iris.Application) {
app.Get("/api/cats", versioning.NewMatcher(versioning.Map{
"1": catsVersionExactly1Handler,
">= 2, < 3": catsV2Handler,
versioning.NotFound: versioning.NotFoundHandler,
}))
}
// How to test:
// Open Postman
// GET: localhost:8080/api/users
// Headers[1] = Accept-Version: "1.9.9" and repeat with
// Headers[1] = Accept-Version: "2.5"
//
// POST: localhost:8080/api/users/new
// Headers[1] = Accept-Version: "1.8.3"
//
// POST: localhost:8080/api/users
// Headers[1] = Accept-Version: "2"
func examplePerParty(app *iris.Application) {
usersAPI := app.Party("/api/users")
// You can customize the way a version is extracting
// via middleware, for example:
// version url parameter, and, if it's missing we default it to "1".
usersAPI.Use(func(ctx iris.Context) {
versioning.SetVersion(ctx, ctx.URLParamDefault("version", "1"))
ctx.Next()
})
// version 1.
usersAPIV1 := versioning.NewGroup(usersAPI, ">= 1, < 2")
usersAPIV1.Get("/", func(ctx iris.Context) {
ctx.Writef("v1 resource: /api/users handler")
})
usersAPIV1.Post("/new", func(ctx iris.Context) {
ctx.Writef("v1 resource: /api/users/new post handler")
})
// version 2.
usersAPIV2 := versioning.NewGroup(usersAPI, ">= 2, < 3")
usersAPIV2.Get("/", func(ctx iris.Context) {
ctx.Writef("v2 resource: /api/users handler")
})
usersAPIV2.Post("/", func(ctx iris.Context) {
ctx.Writef("v2 resource: /api/users post handler")
})
// version 3, pass it as a common iris.Party.
usersAPIV3 := versioning.NewGroup(usersAPI, ">= 3, < 4")
registerAPIV3(usersAPIV3)
}
func catsVersionExactly1Handler(ctx iris.Context) {
ctx.Writef("v1 exactly resource: /api/cats handler")
}
func catsV2Handler(ctx iris.Context) {
ctx.Writef("v2 resource: /api/cats handler")
}
func registerAPIV3(p iris.Party) {
p.Get("/", func(ctx iris.Context) {
ctx.Writef("v3 resource: /api/users handler")
})
// [...]
}