0

I am using https://github.com/kataras/iris Go web framework. I have:

  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 Answer 1

3

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!

3
  • Wow! That was easy! Also is there any harm in using Party as my intention was to differentiate between user route with allRoutes and admin routes with adminRoutes. Is there any performance issue using it like that ?
    – John Cargo
    Sep 10, 2017 at 10:45
  • I have used app.Use to share default title, host, layout file and settings table data. Do you recommend avoiding app.Party? if so, please let me know, why!
    – John Cargo
    Sep 10, 2017 at 10:54
  • 1
    No John, it's not harmful neither any performance cost, if you'd like Party for root routes then continue with that, what ever you like more!!
    – kataras
    Sep 25, 2017 at 15:00

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.