I am building a REST API to do CRUD Operations,
I have a Go struct:
type VisitEntiry struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
UserName string `json:"username"`
PassWord string `json:"password"`
Email string `json:"email"`
}
I am able to save and retrieve VisitEntiries in datastore. So I need to edit visit entity, I want to get the ID that datastore assigns a VisitEntiry to use. I verified that IDs are assigned using Google's datastore dashboard, but how do I get the ID off of a retrieved VisitEntiry?
Cloud you Please help me to write the code to EDIT the Entities.
import (
"encoding/json"
"log"
"net/http"
"golang.org/x/net/context"
"google.golang.org/appengine"
"google.golang.org/appengine/datastore"
)
const KINDNAME = "Vist"
const NAMESPACENAME = "-Test-"
type VisitEntiry struct {
FirstName string `json:"firstname"`
LastName string `json:"lastname"`
UserName string `json:"username"`
PassWord string `json:"password"`
Email string `json:"email"`
}
var visit *VisitEntiry
//SuccessResponse store response
type SuccessResponse struct {
// visit VisitEntiry `json:"entity"`
ID int64 `json:"Id"`
Message string `json:"message"`
}
func init() {
http.HandleFunc("/api/getallvisits", restHandler)
http.HandleFunc("/api/postavisit", restHandler)
}
func restHandler(w http.ResponseWriter, r *http.Request) {
var v VisitEntiry
_ = json.NewDecoder(r.Body).Decode(&v)
json.NewEncoder(w).Encode(v)
visit = &VisitEntiry{
FirstName: v.FirstName,
LastName: v.LastName,
UserName: v.UserName,
PassWord: v.PassWord,
Email: v.Email,
}
switch r.Method {
case "GET":
getallvisitshandler(w, r)
return
case "POST":
putavisthandler(w, r)
return
case "DELETE":
// handleDelete(ed, w, r)
return
default:
//respondErr(w, r, http.StatusNotFound, "is not supported HTTP methods")
}
}
func respond(w http.ResponseWriter, r *http.Request, status int, data interface{}) {
w.WriteHeader(status)
if data != nil {
json.NewEncoder(w).Encode(data)
}
}
func getallvisitshandler(w http.ResponseWriter, r *http.Request) {
var visitslist []VisitEntiry
var ctx context.Context
ctx = appengine.NewContext(r)
ctx, err := appengine.Namespace(ctx, NAMESPACENAME)
if err != nil {
return
}
q := datastore.NewQuery(KINDNAME)
_, err = q.GetAll(ctx, &visitslist)
json.NewEncoder(w).Encode(visitslist)
//log.Printf("%#v Getting values From Datastore - visits ", visitskeys)
}
func putavisthandler(w http.ResponseWriter, r *http.Request) {
var ctx context.Context
keys := make([]*datastore.Key, 1)
ctx = appengine.NewContext(r)
ctx, err := appengine.Namespace(ctx, NAMESPACENAME)
if err != nil {
return
}
keys[0] = datastore.NewIncompleteKey(ctx, KINDNAME, nil)
visitentity, err := datastore.Put(ctx, keys[0], visit)
ID := visitentity.IntID()
value := visitentity.Encode()
//value : = visitentity.Encode()
log.Printf("%#v Getting values From Datastore - visits ", value)
respond(w, r, http.StatusOK, SuccessResponse{ID, "Visit Entity Inserted Successfully! "})
}