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
Release: 2024-11-25 15:29:11
Original
760 people have browsed it

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"},
}
Copy after login

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

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

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
}
Copy after login

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)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template