duanqiao0153 2016-09-30 07:53
浏览 598
已采纳

如何在golang beego中添加过滤器

I have started developing web application where the back end is golang.I m using beego framework to develop this application.Previously i used to program in java.Java have an filter function to filter the request by url.I came to know that we can implement it in beego after reading the documentation.There they have given the following example code

var FilterUser = func(ctx *context.Context) {
    if strings.HasPrefix(ctx.Input.URL(), "/login") {
        return
    }

    _, ok := ctx.Input.Session("uid").(int)
    if !ok {
        ctx.Redirect(302, "/login")
    }
}

beego.InsertFilter("/*", beego.BeforeRouter, FilterUser) 

The Problem is I don't know where to use this block of code....Can someone help me in this.I appreciate your help.Thanks

  • 写回答

1条回答 默认 最新

  • dongyi7669 2016-10-02 20:00
    关注

    You can do something like the following:

    • Set the URL you want to protect in router and the corresponding filter
    • Create a filter function which will be called by the router and check the user

    In more detail:

    // A URL set in router.go
    beego.InsertFilter("/admin/", beego.BeforeRouter, controllers.ProtectAdminPages)
    
    // A Filter that runs before the controller
    // Filter to protect admin pages
    var ProtectAdminPages = func(ctx *context.Context) {
        sess, _ := beego.GlobalSessions.SessionStart(ctx.ResponseWriter, ctx.Request)
        defer sess.SessionRelease(ctx.ResponseWriter)
        // read the session from the request
        ses := sess.Get("mysession")
        if ses != nil {
            s := ses.(map[string]string)
            // get the key identifying the user id
            userId, _ := strconv.Atoi(s["id"])
            // a utility function that searches the database
            // gets the user and checks for admin privileges
            if !utils.UserIsAdmin(userId) {
                ctx.Redirect(301, "/some-other-page")
            }
        } else {
            ctx.Redirect(301, "/")
        }
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 ads仿真结果在圆图上是怎么读数的
  • ¥20 Cotex M3的调试和程序执行方式是什么样的?
  • ¥20 java项目连接sqlserver时报ssl相关错误
  • ¥15 一道python难题3
  • ¥15 用matlab 设计一个不动点迭代法求解非线性方程组的代码
  • ¥15 牛顿斯科特系数表表示
  • ¥15 arduino 步进电机
  • ¥20 程序进入HardFault_Handler
  • ¥15 oracle集群安装出bug
  • ¥15 关于#python#的问题:自动化测试