dougan0529 2018-03-08 18:26
浏览 45
已采纳

如何使用Julien Schmidt的路由器避免Go中的全局变量?

I am developing a RESTful API with Go but owing to app configuration, authentication etc I have quite a few global variables.

I am using Julien Schmidt's httprouter because of popular recommendation and am looking for a feasible way to avoid global variables.

Here is some of the code.

I am using a middleware for authenticating a user using gorrila/securecookie.

func AuthMiddleware(handler httprouter.Handle, isLoggedIn bool) httprouter.Handle {
    return func(w http.ResponseWriter, r *http.Request, ps httprouter.Params) {if isLoggedIn {
            currUser, err := GetCurrentUser(r)

            if currUser.Username != "" {
                handler(w, r, ps)
                return
            }

            responseWriter(w, false, "User not logged in", nil)
            return
        }
        handler(w, r, ps)
    }
}

After this, I want to be able to use the currUser object inside the handler that the request is forwarded to such as this one instead of calling GetCurrentUser once again

func foobar(w http.ResponseWriter, _ *http.Request, _ httprouter.Params) {
    var currQuestion CurrQuestions

    err = Db.db.Raw("SELECT * FROM users WHERE U.user_id = ?", currUser.UserID).Find(&currQuestion).Error
    if err != nil {
        responseWriter(w, false, "Internal Server Error", "")
        return
    }
    responseWriter(w, true, "", GameData{})
}
  • 写回答

1条回答 默认 最新

  • duanju8431 2018-03-10 13:21
    关注

    You can use the context package. Values stored in context are only accessible in the current controller. In your middleware (at the end) do the following:

    ctx := context.WithValue(r.Context(), "User", user)
    r = r.WithContext(ctx)
    handler(w, r, ps)
    

    Now you can fetch this value in you handler:

    user, ok := r.Context().Value("User").(<type of your user struct>)
    

    The string "User" is the key that is used to save the value. You can change it any way you like, but a const is a good idea.

    if ok is true, the user has been fetched and is the correct type. If ok is false, the user was not set or it has the wrong type.

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

报告相同问题?

悬赏问题

  • ¥15 metadata提取的PDF元数据,如何转换为一个Excel
  • ¥15 关于arduino编程toCharArray()函数的使用
  • ¥100 vc++混合CEF采用CLR方式编译报错
  • ¥15 coze 的插件输入飞书多维表格 app_token 后一直显示错误,如何解决?
  • ¥15 vite+vue3+plyr播放本地public文件夹下视频无法加载
  • ¥15 c#逐行读取txt文本,但是每一行里面数据之间空格数量不同
  • ¥50 如何openEuler 22.03上安装配置drbd
  • ¥20 ING91680C BLE5.3 芯片怎么实现串口收发数据
  • ¥15 无线连接树莓派,无法执行update,如何解决?(相关搜索:软件下载)
  • ¥15 Windows11, backspace, enter, space键失灵