3

I am beginner in beego framework, I have completed few R&D inside on it. But I need few helps related routers.

I have created few route with middleware and group router but I need few suggestions from expert.

Let me share example which I did.

Router.go

func init() {
    ns := beego.NewNamespace("/api/v1",

        beego.NSNamespace("/front",
            beego.NSBefore(AuthFilter),
            beego.NSRouter("/user",&controllers.ObjectController{},"*:GetValueByAdmin"),
            beego.NSRouter("/test",&controllers.ObjectController{},"*:GetValueByAdmin"),
            beego.NSRouter("/test",&controllers.ObjectController{},"*:GetValueByAdmin"),
            beego.NSRouter("/test",&controllers.ObjectController{},"*:GetValueByAdmin"),
            beego.NSRouter("/product",&controllers.ObjectController{},"*:GetValueByAdmin"),
        ),


        beego.NSNamespace("/a1",
            beego.NSRouter("/test1",&controllers.ObjectController{},"*:GetValueByAdmin1"),
            beego.NSRouter("/test2",&controllers.ObjectController{},"*:GetValueByAdmin1"),
            beego.NSInclude(
                &controllers.UserController{},
            ),
        ),
    )

    beego.AddNamespace(ns)
}

var AuthFilter = func(ctx *context.Context) {
    // The Authorization header should come in this format: Bearer <jwt>
    // The first thing we do is check that the JWT exists
    header := strings.Split(ctx.Input.Header("Authorization"), " ")
    if header[0] != "Bearer" {
        ctx.Abort(401, "Not authorized")
    }
}

I have created router using Namespace and It is working fine using this url (http://localhost:8080/api/v1/front/test). But I want to remove "front" keyword from URL.

I tried below options like:

  1. I copied code inside "Front" namespace to put outside but My "NSBefore" Will apply all the method which is defined after that. I need 2 group. Before auth and after auth. In after auth, I want to add beego.NSBefore(AuthFilter).

  2. I tried using policy but it will not work as I needed.

    beego.Policy("/api/v1/front/*","*", AuthFilter) beego.Policy("/api/v1/admin/*","*", AuthFilter)

If I will remove front from policy then it will apply all the URL.

Do we have any option to create group router without URL path and it will cover my concept?

kiran malvi
  • 1,058
  • 10
  • 21

0 Answers0