提取登录用户信息以显示 - Golang模板 [英] Fetching Logged in User Info for display - Golang Template

查看:1144
本文介绍了提取登录用户信息以显示 - Golang模板的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我使用 https://github.com/kataras/iris golang web框架。我已完成以下事项: -


  1. 用户注册

  2. 用户验证&登录

  3. 使用用户(表和结构)用户名
  4. 创建并使用键用户名 code

现在,这里是我登录用户的代码: - $ /

  //加载所有数据库和其他所需的值超过

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

在authcheck中间件中

  func authcheck(ctx context.Context){
//加载的会话。
//获取会话密钥isLoggedIn
//如果isLoggedIn ==否或(空)
//重定向到登录页面
// else
ctx.Next()
}

我的会话函数

  func connectSess()* sessions.Sessions {
//创建Gorilla SecureCookie Session
//返回会话
}

现在,我的问题是,如何将记录用户值共享到模板中的所有路由。我的当前选项是: -

  //加载所有数据库和所需值
allRoutes:= app.Party( /,logThisMiddleware,authCheck){

allRoutes.Get(/,func(ctx context.Context){
//再次加载会话
//获取用户名存储在会话中
//针对DB
运行查询//分享用户结构值
//示例ctx.ViewData(user,user)
ctx.View( index.html);
});

allRoutes.Get(dashboard,func(ctx context.Context){
//再次加载会话
//获取会话中存储的用户名
//对DB
运行查询//分享用户结构值
//示例ctx.ViewData(user,user)
ctx.View(index.html);
});
}

但是上面代码的问题是,我将不得不为每条路线编写会话并为我运行的每个路线和共享再次运行查询。



我觉得,必须有更好的方法,而不是为每个 authCheck 中间件和第二个内部 allRoutes.Get 路由。



我需要关于如何优化和用户数据的想法可以通过一次编写代码共享给模板,而不是在每个路由下面重复

  //再次加载会话
//获取存储在会话
中的用户名//对DB
运行查询//分享用户结构值。
//示例ctx.ViewData(user,user)


解决方案

很容易,您可以使用 ctx.Values()。Set / Get 来让路由的处理程序或中间件之间共享某些内容。 p>

  //一次加载会话管理器
sess:= connectSess()

func authCheck(ctx context.Context){
session:= sess.Start(ctx)
//将您的用户加载到此处。
// [...]
//将返回的用户保存到此处理程序链的本地存储中一次。
ctx.Values()。Set(user,user)//< - 重要
}

app.Get(/,func(ctx context 。)(
//从我们的处理程序链的本地存储中获取用户。
user:= ctx.Values()。Get(user)//< - 重要

//将{{.user}}绑定到用户实例
ctx.ViewData(user,user)
//渲染模板文件
ctx.View(index.html)
})

app.Get(dashboard,func(ctx context.Context){
//同样,get (用户)//< - 重要

ctx.ViewData(user ,用户)
ctx.View(index.html)
})



< 但是我有一些笔记给你,阅读它们if你有更多的时间。



当你在根目录/时,你不必为它创建一个派对( .Party )以添加mi ddlewares(开始(使用)或完成( Done )),只需使用 iris。应用程序实例, app.Use / Done



不要写这个:

  allRoutes:= app.Party(/,logThisMiddleware,authCheck){

allRoutes。 Get(/,myHandler)
}

做到这一点:


$ b $

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

阅读和理解比较容易

我还注意到您在函数,编辑器和 gocode 中使用; code>工具将删除这些,当你使用Go Programming Language编写程序时,你不应该这样做,删除所有;



最后,请阅读文档和示例,其中许多内容位于 https://github.com/kataras/iris/tree/master/_examples ,希望你最好!


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)

解决方案

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!

这篇关于提取登录用户信息以显示 - Golang模板的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆