dongtong1226 2017-09-09 12:01
浏览 197
已采纳

获取登录的用户信息以显示-Golang模板

I am using https://github.com/kataras/iris golang web framework. I have done below thing :-

  1. User Registered
  2. User Verified & Logged in
  3. Session created and set with key username with user (table & struct) username

Now, here is my code for logged in user :-

// Loaded All DB and other required value above

allRoutes := app.Party("/", logThisMiddleware, authCheck) {
    allRoutes.Get("/", func(ctx context.Context) {
        ctx.View("index.html");
    });
}

In authcheck middleware

func authcheck(ctx context.Context) {
    // Loaded session.
    // Fetched Session key "isLoggedIn"
    // If isLoggedIn == "no" or "" (empty)
    // Redirected to login page
    // else
    ctx.Next()
}

My Session function

func connectSess() *sessions.Sessions {
    // Creating Gorilla SecureCookie Session
    // returning session
}

Now, my problem is, how do I share Logged User value to all routes in template. My Current option is :-

// Loaded all DB and required value
allRoutes := app.Party("/", logThisMiddleware, authCheck) {

    allRoutes.Get("/", func(ctx context.Context) {
        // Load Session again
        // Fetch username stored in session
        // Run Query against DB
        // Share the user struct value.
        // Example ctx.ViewData("user", user)
        ctx.View("index.html");
    });

    allRoutes.Get("dashboard", func(ctx context.Context) {
        // Load Session again
        // Fetch username stored in session
        // Run Query against DB
        // Share the user struct value.
        // Example ctx.ViewData("user", user)
        ctx.View("index.html");
    });
}

But problem with above code is, I will have to write session for each route and run query again for each route I run and than share.

I feel, there must be better way of doing it , rather than loading session twice for each route one in authCheck middleware and second inside allRoutes.Get route.

I need ideas on how this can be optimised and user data can be shared to template by just writing code one time and not repeating below for each route

        // Load Session again
        // Fetch username stored in session
        // Run Query against DB
        // Share the user struct value.
        // Example ctx.ViewData("user", user)
  • 写回答

1条回答 默认 最新

  • dream518518518 2017-09-10 10:10
    关注

    it's easy you can use the ctx.Values().Set/Get to make something shareable between your route's handlers or middleware(s).

    // load session manager once
    sess := connectSess()
    
    func authCheck(ctx context.Context) {
        session := sess.Start(ctx)
        // Load your user here.
        // [...]
        // Save the returning user to the local storage of this handlers chain, once. 
        ctx.Values().Set("user", user) // <-- IMPORTANT
    }
    
    app.Get("/", func(ctx context.Context) {
        // Get the user from our handlers chain's local storage.
        user := ctx.Values().Get("user") // <-- IMPORTANT
    
        // Bind the "{{.user}}" to the user instance.
        ctx.ViewData("user", user)
        // Render the template file.
        ctx.View("index.html")
    })
    
    app.Get("dashboard", func(ctx context.Context) {
        // The same, get the user from the local storage...
        user := ctx.Values().Get("user") // <-- IMPORTANT
    
        ctx.ViewData("user", user)
        ctx.View("index.html")
    })
    

    That's all, pretty simple, right?

    But I have some notes for you, read them if you have more time.

    When you're on root "/" you don't have to create a party for it(.Party) in order to add middlewares (begin(Use) or finish(Done)), use just the iris.Application instance, app.Use/Done.

    Don't write this:

    allRoutes := app.Party("/", logThisMiddleware, authCheck) {
    
        allRoutes.Get("/", myHandler)
    }
    

    Do that instead:

    app.Use(logThisMiddleware, authCheck)
    app.Get("/", myHandler)
    

    It's easier to read and understand.

    I've also noticed that you're using ; at the end of your functions, your editor and gocode tool will remove those, when you write a program using the Go Programming Language you shouldn't do that, remove all ;.

    Last, please read the documentation and the examples, we have many of them at https://github.com/kataras/iris/tree/master/_examples , hopes you the best!

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 关于#python#的问题:求帮写python代码
  • ¥20 MATLAB画图图形出现上下震荡的线条
  • ¥15 LiBeAs的带隙等于0.997eV,计算阴离子的N和P
  • ¥15 关于#windows#的问题:怎么用WIN 11系统的电脑 克隆WIN NT3.51-4.0系统的硬盘
  • ¥15 来真人,不要ai!matlab有关常微分方程的问题求解决,
  • ¥15 perl MISA分析p3_in脚本出错
  • ¥15 k8s部署jupyterlab,jupyterlab保存不了文件
  • ¥15 ubuntu虚拟机打包apk错误
  • ¥199 rust编程架构设计的方案 有偿
  • ¥15 回答4f系统的像差计算