gpt4 book ai didi

google-app-engine - 通过将 key 存储到 session golang 中来更快地加载页面

转载 作者:数据小太阳 更新时间:2023-10-29 03:26:44 25 4
gpt4 key购买 nike

我正在尝试更快地加载动态页面。我正在将 Twitter 克隆作为一项学习任务。我正在遵循以下方法

  1. 当有人发推文时,将推文存储在数据存储中,并在内存缓存中对其进行保护 { key.string(), json.Marshal(tweet) }

  2. 我在用户主页时间线中推送推文。主页时间线是一个 []*datastore.Key,它存储在用户 session 中(先复制到内存缓存中,然后再复制到数据库中)。

  3. 当用户打开她的主页时,主页会尝试从 session 中获取 key ,如果找不到则进行数据存储查询。

  4. 一旦我获得 key ,我就从内存缓存中获取推文(如果不是,则从数据库中获取)

我卡在了第 3 步。

在第一种情况下,我得到了正确的信息,但在字符串 slice 中(不在 []*datastore.Key 中)。

在第二种情况下我得到这个错误

2016/09/03 17:23:42 http: panic serving 127.0.0.1:47104: interface conversion: interface is []interface {}, not []datastore.Key

请帮助我哪里出错了,有没有更好的方法。

案例一

func GetKeys(req *http.Request, vars ...string) []interface{} {
//GetKeys - get the keys
s, _ := GetGSession(req)
var flashes []interface{}
key := internalKey
if len(vars) > 0 {
key = vars[0]
}

if v, ok := s.Values[key]; ok {
// Drop the flashes and return it.
// delete(s.Values, key)
flashes = v.([]interface{})
}
return flashes
}

案例2

//GetHTLKeys - get the hometimeline keys
func GetHTLKeys(req *http.Request, vars ...string) []datastore.Key {
s, _ := GetGSession(req)

var keyList []datastore.Key

key := internalKey
if len(vars) > 0 {
key = vars[0]
}

if v, ok := s.Values[key]; ok {
keyList = v.([]datastore.Key)
}
return keyList
}

最佳答案

您的问题是您不能断言 []interface{}[]datastore.Key。这是因为它们不同。此时您可以做的是向 []interface{} 键入 assert v,然后遍历 slice 并为每个元素键入 assert。

这是一个演示这个的例子(playground version):

type I interface {
I()
}

type S struct{}

func (s S) I() {
fmt.Println("S implements the I interface")
}

// Represents you getting something out of the session
func f(s S) interface{} {
return []interface{}{s}
}

func main() {
v := f(S{})

//v2 := v.([]I) would panic like in your example.

v2, ok := v.([]interface{})
if !ok {
// handle having a non []interface{} as a value
}
for _, v3 := range v2 {
v4, ok := v3.(I)
if !ok {
// handle having a non-I in the slice
}
v4.I() //you definitely have an I here
}

}

关于google-app-engine - 通过将 key 存储到 session golang 中来更快地加载页面,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/39310126/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com