384 字
2 分钟
golang模板中使用array的索引获取value

起因#

想要搞一个session的网站,后台是ldap验证的,当用户验证后,生成cookie,记录对应的session,然后在session过期前就可以一直进行相关的操作,而不需要每次操作都要验证。

过程#

开始的时候很顺利,但是当修改了模版后,莫名的cookie创建后,不能写入了。 就是login后,直接退出,application中的cookie项目为空了。

开始没有头绪,后来就发现肯定是模版设计的有问题。总是出不来效果。

因为当从session中取简单值,然后将模版设定为简单的那种,就可以显示。

搞这个模版折腾了接近一天的时间。

后来数据结构就是[][]string这样了,不搞什么struct了。累了。

模版中这样写:

<table>
<thead>
<tr>
<th scope="col">ID</th>
<th scope="col">HostName</th>
<th scope="col">OS</th>
</tr>
</thead>
<tfoot>
<tr>
<td>End</td>
</tfoot>
<tbody>
{{ range $_,$item:=.Result }}
<tr>
<td> {{ index $item 0 }}</td>
<td> {{ index $item 1 }}</td>
<td> {{ index $item 2 }}</td>
</tr>
{{ end }}
</tbody>
</table>

这里的Result是提交给template用于解析的类型为[][]string的数组。 如果这个Result的值是这样的[[“1“,“server1”,“Windows]],那么{{ index $item 0}}, 就是表示[“1“,“server1”,“Windows]中的index为0的值,依次类推。

省的搞什么struct这样的,真的好累。

还有最后发现一个问题说“securecookie: the value is too long”, 再说吧,一般人没有这么大的数据量。。

后台用redis处理的方式,下面再来看了。

补充: 还是看看这里的后台方案吧: https://github.com/gorilla/sessions#store-implementations

golang模板中使用array的索引获取value
https://dididudu998.github.io/posts/golang模版/
作者
滴滴嘟嘟
发布于
2021-01-21
许可协议
CC BY-NC-SA 4.0