IRIS 系列(二) 路由

我考虑一个web框架时,首先建立一个简单的例子,然后考虑如何书写路由,是否支持Restful 风格。
当路由多了,管理起来比较麻烦,但IRIS 提供一种高效的办法,就是路由分组。路由分组有可能将其功能形容的有些小,我认为更确切的说法是路由树。

在 IRIS 的底层router 包提供Party 接口,实现路由分组功能

Party 接口说明

Party is just a group joiner of routes which have the same prefix and share same middleware(s) also.Party could also be named as 'Join' or 'Node' or 'Group' , Party chosen because it is fun.

中文翻译:
Party是一组具有相同前缀并共享相同中间件的路由。 Party也可以命名为'Join'、'Node'、'Group',之所以选择Party是因为它更生动。

在Party 接口提供了两个关键函数

Party(relativePath string, middleware ...context.Handler) Party

PartyFunc(relativePath string, partyBuilderFunc func(p Party)) Party

两个函数功能是相同的,只是用法不同。我们通过实际例子来理解两个函数的用法。

package main

import (
    "github.com/kataras/iris/v12"
)

func main() {

    app := iris.New()

    v1 := app.Party("/v1")
    // http://localhost:8080/v1/hello
    v1.Get("/hello", func(ctx iris.Context) {
        ctx.WriteString("welcome")
    })

    app.PartyFunc("/basic", func(basic iris.Party) {
        basic.PartyFunc("/users", func(users iris.Party) {
            // http://localhost:8080/basic/users
            users.Post("/", CreateUser)
            // http://localhost:8080/users/123  method :Put 123 为user id
            users.Put("/{id:string}", UpdateUser)
            // http://localhost:8080/users/123  method:Delete 123 user id
            users.Delete("/{id:string}", DeleteUser)
        })
    })

    app.Run(iris.Addr(":8081"), iris.WithoutServerError(iris.ErrServerClosed))
}

func CreateUser(ctx iris.Context) {
    ctx.WriteString("create user")
}

func DeleteUser(ctx iris.Context) {
    ctx.WriteString("delete user")
}

func UpdateUser(ctx iris.Context) {
    ctx.WriteString("update user")
}

大家根据上述解释就可以理解路由分组。有问题请留言。本系列完成会提供更加实际的代码。

©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。