Home >Backend Development >Golang >How Can I Create Dynamic Entities in Go\'s Google App Engine Datastore?

How Can I Create Dynamic Entities in Go\'s Google App Engine Datastore?

Mary-Kate Olsen
Mary-Kate OlsenOriginal
2024-11-25 15:29:11778browse

How Can I Create Dynamic Entities in Go's Google App Engine Datastore?

Achieving Dynamic Properties in Go's Google App Engine Datastore

In Python's App Engine, the Expando Model enables the dynamic assignment of attributes to entities without prior declaration. This article explores how to achieve similar functionality in Go using the Google App Engine Datastore.

The PropertyLoadSaver Interface

The key to defining dynamic entities in Go is the PropertyLoadSaver interface. By implementing this interface, you gain the ability to dynamically construct an entity's properties at save time.

Using PropertyList from the Go App Engine Platform

The Go App Engine platform offers the PropertyList type, which is a list of Property instances and implements the PropertyLoadSaver interface. By leveraging PropertyList, you can create dynamic entities without implementing the interface yourself.

props := datastore.PropertyList{
    {Name: "time", Value: time.Now()},
    {Name: "email", Value: "johndoe@example.com"},
}

To save this list as an entity, you can use:

key, err := datastore.Put(c, k, &props)

Implementing PropertyLoadSaver for Custom Types

For further flexibility, you can implement the PropertyLoadSaver interface on your own custom types, such as maps.

type DynEnt map[string]interface{}

func (d *DynEnt) Load(props []datastore.Property) error {
    for _, p := range props {
        (*d)[p.Name] = p.Value
    }
    return nil
}

func (d *DynEnt) Save() (props []datastore.Property, err error) {
    for k, v := range *d {
        props = append(props, datastore.Property{Name: k, Value: v})
    }
    return
}

With this custom implementation, you can now load and save dynamic entities with ease:

d := DynEnt{"email": "johndoe@example.com", "time": time.Now()}
key, err := datastore.Put(c, k, &d)

This approach grants you full control over the property definitions of your dynamic entities.

The above is the detailed content of How Can I Create Dynamic Entities in Go's Google App Engine Datastore?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn