dt2002 2018-01-02 03:18
浏览 70

在Golang中检查HTML文件中的用户会话

How to check the user login session directly in the HTML files? I already searched it on google but I can't find the checking session directly in the html file, is it not possible to do that?

The only thing I can found is by pass it through ExecuteTemplate(), is that the only thing I can do?

  • 写回答

2条回答 默认 最新

  • doubo1711 2018-01-02 08:46
    关注

    I think from your description you have a session variable accessible within the .go file (the handlerfunc), and wish to use it in the html file. This is relatively simple, it's just a value. Yes, passing it through ExecuteTemplate is the right approach. The session is just a cookie sent with the request to your server from the browser, it's there in the request headers.

    You could set a func in your set of funcs for the template which accessed some sort of global variable, but then you'd get into problems with syncing across goroutines (every request handler runs in a goroutine), so the simpler approach is best.

    You should not be trying to perform operations on the session in a template like decrypting it and extracting a user id - this is more suited to your handlers and far more secure there and not in the template.

    First extract it from the cookie using your preferred library (you are encrypting your sessions right?), then add it to the view context (let's say you use a map of values).

    // use a lib like gorilla sessions
    session, err := store.Get(r, "session-name")
    userID := session.Get("user")
    
    // store data (here in a map[string]interface{})
    data := make(map[string]interface{})
    data["userID"] = userID 
    
    // Send this data to the view
    t.Execute(w, data) // Sets the . variable in templates
    

    Then in the view, just use something like this to access the values you need:

    {{ .userID }}
    

    Alternatively yes you can just use javascript to access the session, but you'd need to know how it is encrypted, which is probably a security hole if it contains any information of value - anything js can get at your user can get at too.

    评论

报告相同问题?

悬赏问题

  • ¥15 c语言怎么用printf(“\b \b”)与getch()实现黑框里写入与删除?
  • ¥20 怎么用dlib库的算法识别小麦病虫害
  • ¥15 华为ensp模拟器中S5700交换机在配置过程中老是反复重启
  • ¥15 java写代码遇到问题,求帮助
  • ¥15 uniapp uview http 如何实现统一的请求异常信息提示?
  • ¥15 有了解d3和topogram.js库的吗?有偿请教
  • ¥100 任意维数的K均值聚类
  • ¥15 stamps做sbas-insar,时序沉降图怎么画
  • ¥15 买了个传感器,根据商家发的代码和步骤使用但是代码报错了不会改,有没有人可以看看
  • ¥15 关于#Java#的问题,如何解决?