Search code examples
godatastore

Unable to parse string to datastore.Key


With reference to this question, I am trying to convert a datastore key from the Form to int64 and with the help of that key, trying to update a record in the datastore. I tried exactly the same code as in the answer selected in the reference link, but I get an error which says, Unable to parse key. strconv.ParseInt: parsing "/Users,6248007768440574": invalid syntax

The value I'm passing from the form is a datastore key of the format /Users,6248007768440574. I realize that the syntax error is because of this. Could anyone please help me in how to go about with this issue? Or, is there a method to convert a string to *datastore.Key? Any help will be appreciated


Solution

  • ParseInt returns an error because the string "/Users,6248007768440574" is not an integer. A substring is an integer, but not the entire string.

    The string in the question was created by calling Key.String. The datastore package does not provide a way to parse the output from this method. Here's a simple parser for the case where there are no ancestor keys:

    var keyPat = regexp.MustCompile(`^/([^\.]*),(\d+)$`)
    
    func parseKey(s string) (*datastore.Key, error) {
        m := keyPat.FindStringSubmatch(s)
        i := strings.Index(s, ",")
        if i < 0 {
            return nil, errors.New("bad format")
        }
        n, err := strconv.ParseInt(m[2], 10, 64)
        if err != nil {
            return nil, err
        }
        return datastore.IDKey(m[1], n, nil), nil
    }
    

    The the Encode method and Decode function are the preferred way to convert a key to and from a machine readable string.