Datsik
Datsik

Reputation: 14824

How do I set a persistent global template variable from the controller using Revel / Golang

I'm new to Golang and I'm switching over from Node.js server to a Golang server, I'm trying to rewrite an app I had previously written for Node.

I want to set Template variables when a user is signed in, but I'm not sure how and yes, I've tried googling it.

This is my register user controller:

func (c User) RegisterUser(user_email, user_password,
    user_password_confirmation, user_first_name,
    user_last_name string) revel.Result {

    // Validate Email
    c.Validation.Required(user_email).Message("Username is required")
    c.Validation.Email(user_email).Message("Email is not a valid email")
    c.Validation.MinSize(user_email, 5).Message("Email must be greater than 5 characters")
    // Validate Password
    c.Validation.Required(user_password).Message("Password is required")
    c.Validation.MinSize(user_password, 5).Message("Password must be greater than 5 characters.")
    // Validate Password Confirmation
    c.Validation.Required(user_password_confirmation).Message("Password Confirmation is required")
    c.Validation.MinSize(user_password_confirmation, 5).Message("Password must be greater than 5 characters.")
    c.Validation.Required(user_password == user_password_confirmation).Message("Your passwords do not match")
    // Validate First Name
    c.Validation.Required(user_first_name).Message("First Name is required")
    c.Validation.MinSize(user_first_name, 3).Message("Your First Name must be greater than 3 characters")
    // Validate Last Name
    c.Validation.Required(user_last_name).Message("Last Name is required")
    c.Validation.MinSize(user_last_name, 3).Message("Your Last Name must be greater than 3 characters")

    // If anything wasn't right, set flash and display errors to user
    if c.Validation.HasErrors() {
        c.Validation.Keep()
        c.FlashParams()
        return c.Redirect(User.Register)
    }

    // Hash The Users Password
    password := []byte(user_password_confirmation)
    hashedPassword, err := bcrypt.GenerateFromPassword(password, 10)
    if err != nil {
        c.Flash.Error("Invalid Username or Password Combination")
        return c.Redirect(User.Register)
    }

    // Connect to database
    db, err := sql.Open("mysql", "root:******@/WebRTC")
    if err != nil {
        c.Flash.Error("Unable to connect to database. Try again later!")
        return c.Redirect(User.Register)
    }
    defer db.Close()

    // Ping the database, ensure there is a connection
    err = db.Ping()
    if err != nil {
        c.Flash.Error("Unable to connect to database. Try again later!")
        return c.Redirect(User.Register)
    }

    // Prepare SQL Statement for Security
    stmtIns, err := db.Prepare("INSERT INTO users (user_email, user_first_name, user_last_name, " +
        "user_password_hash, user_created_at, user_created_ip, user_last_ip) VALUES (?, ?, ?, ?, ?, ?, ?)")

    if err != nil {
        c.Flash.Error("Unable to Register you. Please try again later")
        return c.Redirect(User.Register)
    }
    defer stmtIns.Close()

    // Insert Data into Database
    _, err = stmtIns.Exec(user_email, user_first_name, user_last_name, hashedPassword,
        time.Now().Local(), c.Request.RemoteAddr, c.Request.RemoteAddr)
    if err != nil {
        c.Flash.Error("Unable to register you. Please try again later")
        return c.Redirect(User.Register)
    }

    // Here I want to add the global template variable
    return c.Redirect(User.Register)
}

I've read about c.RenderArgs but it doesn't seem to do what I want it to.

I want to be able to set the users' username, so that I can display it in the navbar so that they know they're logged in.

Upvotes: 1

Views: 827

Answers (1)

Ian
Ian

Reputation: 705

You are on the right track if you are using c.RenderArgs unless I have misunderstood your intentions.

Here's an example (or rather, a walkthrough) of how you may use it (taken from Revel's booking sample app):

  1. init.go: Register an interceptor to add the user's information before an action is taken (AddUser will be fired before Render).

  2. app.go: Check if the user is connected and if so, store the user's data in the RenderArgs map like so:

c.RenderArgs["user"] = user

  1. Line 31 deals with the model.

  2. header.html: Pass the username template variable in.

I hope this helps.

EDIT: I should probably add that the user's username is stored in a session upon login. It's used to retrieve more information.

Upvotes: 1

Related Questions