drt3751 2016-09-03 18:29
浏览 51
已采纳

通过将密钥存储到会话golang中来更快地加载页面

I am trying to load dynamic page faster. I am making twitter clone as a learning assignment. I am following below approach

  1. When somebody tweets, store the tweet in datastore and safe the same in memcache { key.string(), json.Marshal(tweet) }

  2. I push the tweet in User home time line. The home time line is a []*datastore.Key, which is stored in user session (which get copied in memcache and then in DB).

  3. When user open her homepage, the homepage try to get the Keys from session, if not found then it make a datastore query.

  4. Once i get the keys I fetch the tweets from memcache (if not then from db)

I am stuck at step 3.

In first case I am getting the correct information but in string slices (not in []*datastore.Key).

In second case I getting this error

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

Kindly help me where I am going wrong and is there a better way.

case 1

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
}

Case2

//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
}
  • 写回答

1条回答 默认 最新

  • dsxsou8465 2016-09-03 20:17
    关注

    Your issue is that you can't assert an []interface{} is a []datastore.Key. This is because they are different. What you can do at this point, is type assert v to a []interface{} then loop through the slice and type assert each element.

    Here is an example demonstrating this (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 
        }
    
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?