如何使用 Go 處理 Google App Engine 資料儲存體中的動態屬性?
Nov 20, 2024 am 02:33 AM如何在Go on Google App Engine 資料儲存中實現動態屬性
Google App Engine 資料儲存為Web 應用程式提供了強大的資料儲存解決方案,提供了靈活性和可擴展性。有時,需要儲存具有動態屬性的數據,這意味著未事先聲明的屬性。這可以透過利用 Google App Engine 的 PropertyLoadSaver 介面在 Go 中實現。
PropertyLoadSaver 介面
PropertyLoadSaver 介面可讓您定義如何將實體的屬性載入和儲存到資料儲存區。透過實現此接口,您可以控制動態屬性處理。
PropertyList 類型
Go App Engine 平台提供了實作 PropertyLoadSaver 介面的 PropertyList 類型。 PropertyList 本質上是屬性的一部分,允許您動態新增和刪除屬性。
PropertyList 用法範例
要使用PropertyList 建立具有動態屬性的實體,請依照下列步驟操作:
import "google.golang.org/appengine/datastore" // Create a PropertyList to hold the dynamic properties. props := datastore.PropertyList{ datastore.Property{Name: "time", Value: time.Now()}, datastore.Property{Name: "email", Value: "[email protected]"}, } // Create an incomplete key for the new entity. k := datastore.NewIncompleteKey(ctx, "DynEntity", nil) // Save the entity using the PropertyList. key, err := datastore.Put(ctx, k, &props)
登入後複製
此程式碼片段建立一個具有「DynEntity」類型和兩個動態屬性的實體:「時間」和「電子郵件」。 PropertyList 將會儲存為實體的值。
實作您自己的 PropertyLoadSaver(可選)
如果需要,您也可以實作您自己的 PropertyLoadSaver。以下是使用名為「DynEnt」的自訂類型的範例:
import "google.golang.org/appengine/datastore" 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) error { for k, v := range *d { props = append(props, datastore.Property{Name: k, Value: v}) } return err }
登入後複製
此 DynEnt 類型可用於儲存具有動態屬性的實體,如下所示:
import "google.golang.org/appengine/datastore" // Create a DynEnt with dynamic properties. d := DynEnt{"email": "[email protected]", "time": time.Now()} // Create an incomplete key for the new entity. k := datastore.NewIncompleteKey(ctx, "DynEntity", nil) // Save the entity using the DynEnt. key, err := datastore.Put(ctx, k, &d)
登入後複製
以上是如何使用 Go 處理 Google App Engine 資料儲存體中的動態屬性?的詳細內容。更多資訊請關注PHP中文網其他相關文章!
本網站聲明
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn

熱門文章
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章
倉庫:如何復興隊友
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
擊敗分裂小說需要多長時間?
3 週前
By DDD
R.E.P.O.能量晶體解釋及其做什麼(黃色晶體)
1 週前
By 尊渡假赌尊渡假赌尊渡假赌
Hello Kitty Island冒險:如何獲得巨型種子
3 週前
By 尊渡假赌尊渡假赌尊渡假赌
公眾號網頁更新緩存難題:如何避免版本更新後舊緩存影響用戶體驗?
3 週前
By 王林

熱門文章標籤

記事本++7.3.1
好用且免費的程式碼編輯器

SublimeText3漢化版
中文版,非常好用

禪工作室 13.0.1
強大的PHP整合開發環境

Dreamweaver CS6
視覺化網頁開發工具

SublimeText3 Mac版
神級程式碼編輯軟體(SublimeText3)