普通网友 2015-01-11 23:30
浏览 36
已采纳

如何使用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.

  • 写回答

1条回答 默认 最新

  • dongyun51582 2015-01-12 02:32
    关注

    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.

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

报告相同问题?

悬赏问题

  • ¥15 outlook无法配置成功
  • ¥30 这是哪个作者做的宝宝起名网站
  • ¥60 版本过低apk如何修改可以兼容新的安卓系统
  • ¥25 由IPR导致的DRIVER_POWER_STATE_FAILURE蓝屏
  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题