duanrou5680 2014-05-06 16:56
浏览 9
已采纳

如何使用Go将密钥存储在数据存储对象中?

I'm trying to put a *Key of a Location

type Location struct 
    City, State, Country string
}

in a Band

type Band struct {
    Name string
    LocationId *datastore.Key
    Albums []Album
}

When I first create a Location, add the key, then try to retrieve the Location values, the strings all come out empty. If I then add a new Band, the location I created shows up fine, and using that location in a new Band works. I'm using incomplete keys:

func AddLocation(value Location, rq *http.Request) (*datastore.Key, error) {
    c := appengine.NewContext(rq)
    key := datastore.NewIncompleteKey(c, config.LOCATION_TYPE, nil)
    _, err := datastore.Put(c, key, &value)

    return key, err
}

Using an existing Location is as follows:

case "existing":
    rawId := rq.FormValue("location_id")
    q := strings.Split(rawId, ",")
    x := q[1]
    id_int, e := strconv.ParseInt(x, 10, 64)
    if e != nil {
        message = e.Error()
    }
    locationId = datastore.NewKey(c, config.LOCATION_TYPE, "", id_int, nil)
    //  message = "not implemented yet"
    break

Using the key from the original Put didn't seem to work, so I resorted to:

case "new":
    location := model.Location{rq.FormValue("city"), rq.FormValue("state"), rq.FormValue("country")}
    var err error
    _, err = model.AddLocation(location, rq)
    if err != nil {
        message = "Location add: " + err.Error()
    }
    q := datastore.NewQuery(config.LOCATION_TYPE).Filter("City =", location.City).
        Filter("State =", location.State).Filter("Country =", location.Country).
        KeysOnly()
    keys, err := q.GetAll(c, nil)
    if err != nil {
    message = "Location add: " + err.Error()
    }
    var k *datastore.Key
    for _, key := range keys {
        k = key
        break
    }
    locationId = k
    break

And that didn't work right either. What am I not getting?

  • 写回答

1条回答 默认 最新

  • duanchuang6978 2014-05-08 00:10
    关注

    When you call datastore.Put with an incomplete key, the key's id is not filled in. The returned key has it. You're ignoring the return value from datastore.Put with _.

    Your AddLocation func should look like this:

    func AddLocation(value Location, rq *http.Request) (*datastore.Key, error) {
        c := appengine.NewContext(rq)
        key := datastore.NewIncompleteKey(c, config.LOCATION_TYPE, nil)
        // this line updates the key with accurate information
        key, err := datastore.Put(c, key, &value)
    
        return key, err
    }
    
    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论

报告相同问题?

悬赏问题

  • ¥15 WPF 大屏看板表格背景图片设置
  • ¥15 这个主板怎么能扩出一两个sata口
  • ¥15 不是,这到底错哪儿了😭
  • ¥15 2020长安杯与连接网探
  • ¥15 关于#matlab#的问题:在模糊控制器中选出线路信息,在simulink中根据线路信息生成速度时间目标曲线(初速度为20m/s,15秒后减为0的速度时间图像)我想问线路信息是什么
  • ¥15 banner广告展示设置多少时间不怎么会消耗用户价值
  • ¥16 mybatis的代理对象无法通过@Autowired装填
  • ¥15 可见光定位matlab仿真
  • ¥15 arduino 四自由度机械臂
  • ¥15 wordpress 产品图片 GIF 没法显示