// WriteJsonResponse does the same as ToJson. But also writes the JSON // generated to http.ResponseWriter. In case of error, writes that error // instead, in this format: // // { // "code": "E_ERROR", // "message": "error message" // } func (r *Result) WriteJsonResponse(w http.ResponseWriter) { data, err := r.ToJson() if err != nil { x.SetStatus(w, x.E_ERROR, err.Error()) return } _, err = w.Write(data) if err != nil { x.SetStatus(w, x.E_ERROR, err.Error()) return } }
func (h *Helper) CreateOrUpdate(w http.ResponseWriter, r *http.Request) { var e Entity if ok := x.ParseRequest(w, r, &e); !ok { return } if e.Child != nil { if len(e.Child.Id) > 0 { x.SetStatus(w, x.E_INVALID_REQUEST, "Child cannot have id specified") return } } if len(e.Id) == 0 || len(e.Kind) == 0 { x.SetStatus(w, x.E_INVALID_REQUEST, "No id or kind specified") return } if len(e.Source) == 0 { x.SetStatus(w, x.E_INVALID_REQUEST, "No source specified") return } n := api.Get(e.Kind, e.Id).SetSource(e.Source) for key, val := range e.Data { n.Set(key, val) } if e.Child != nil { c := n.AddChild(e.Child.Kind) if len(e.Child.Source) > 0 { c.SetSource(e.Child.Source) } for key, val := range e.Child.Data { c.Set(key, val) } } if err := n.Execute(h.ctx); err != nil { x.SetStatus(w, x.E_ERROR, err.Error()) return } x.SetStatus(w, x.E_OK, "Stored") }
func read(w http.ResponseWriter, r *http.Request) { id, ok := x.ParseIdFromUrl(r, "/read/") if !ok { return } // API usage to read data. q := api.NewQuery("hack", id).UptoDepth(10) result, err := q.Run(c) if err != nil { x.SetStatus(w, x.E_ERROR, err.Error()) return } result.WriteJsonResponse(w) }