Exemple #1
0
// handle the data request, calling the optional callback when complete
// handles GET/POST with no key to get the whole collection or create a new item
// handles GET/PUT/DELETE with a key to get, update and remove the given item
// this method will validate data and check permissions
// after completion, the optional callback is called with key and item reference
//  item is nil for DELETE and GET(all)
//  key is nil for GET(all)
//  method specifies which HTTP method was used
func (self *dataHandler) handleRequest(ancestor *datastore.Key,
	callback func(method string, key *datastore.Key, item Ided)) {
	id := getID(self.r)
	var key *datastore.Key
	var item Ided
	// handle request with no specific ID
	if len(id) == 0 {
		switch self.r.Method {
		case "GET":
			// we return a JSON list of all items
			self.getAll(ancestor)
		case "POST":
			// we create a new item and return it
			key, item = self.createEntry(ancestor)
		default:
			check(ErrUnsupported)
		}
	} else {
		// we are working with a specific id, validate it
		var err error
		key, err = datastore.DecodeKey(id)
		check(err)
		if key.Incomplete() {
			check(ErrUnknownItem)
		}
		self.checkUser(key)
		// handle the get, update and delete methods
		switch self.r.Method {
		case "GET":
			item = self.get(key)
		case "PUT":
			item = self.update(key)
		case "DELETE":
			self.delete(key)
		default:
			check(ErrUnsupported)
		}
	}
	// call the callback if we have one
	if callback != nil {
		callback(self.r.Method, key, item)
	}
}