Example #1
0
// PostOrPut is the common code between put and post requests.
// TODO: This is partially incorrect according to the spec.
// PUT without an id in the uri is invalid and should return a BadRequest error.
// Fix this to comply to with the spec.
func (r Resource) PostOrPut(rw http.ResponseWriter, req *http.Request) {
	var (
		vars   = mux.Vars(req)
		query  = req.URL.Query()
		entity Entity
		resp   interface{}
		err    error
	)
	if entity, err = r.manager.ParseJSON(req.Body); err != nil {
		http.Error(rw, err.Error(), http.StatusBadRequest)
		return
	}
	id := vars["id"]
	if id == "" && entity.HasId() {
		id = entity.GetId()
	}
	if id != "" {
		resp, err = r.manager.UpdateEntity(id, entity, query)
	} else {
		resp, err = r.manager.CreateEntity(entity, query)
	}
	if err != nil {
		http.Error(rw, err.Error(), http.StatusInternalServerError)
		return
	}
	util.WriteJSON(resp, rw)
}
Example #2
0
// Get is the delegate http handler for get requests for this resource.
func (r Resource) Get(rw http.ResponseWriter, req *http.Request) {
	resp := r.get(rw, req)
	if resp != nil {
		util.WriteJSON(resp, rw)
	}
}