コード例 #1
0
ファイル: server.go プロジェクト: plar/memdb
//
// POST /values/{key}/{lock_id}?release={true, false}
//
// Attempt to update the value of {key} to the value given in the POST body according to the following rules:
//
// If {key} doesn't exist, return 404 Not Found
// If {key} exists but {lock_id} doesn't identify the currently held lock, do no action and respond immediately with 401 Unauthorized.
// If {key} exists, {lock_id} identifies the currently held lock and release=true, set the new value, release the lock and invalidate {lock_id}. Return 204 No Content
// If {key} exists, {lock_id} identifies the currently held lock and release=false, set the new value but don't release the lock and keep {lock_id} value. Return 204 No Content
//
func (s *Server) Update(w http.ResponseWriter, r *http.Request) {
	vars := mux.Vars(r)

	// handle key var
	rawKey, exists := vars["key"]
	if !exists {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	key := memdb.Key(rawKey)

	// handle lock_id var
	rawLockId, exists := vars["lock_id"]
	if !exists {
		w.WriteHeader(http.StatusBadRequest)
		return
	}
	lockId := memdb.LockID(rawLockId)

	// handle release query param
	release, err := strconv.ParseBool(vars["release"])
	if err != nil {
		w.WriteHeader(http.StatusBadRequest)
		return
	}

	// read POST Body
	body, err := ioutil.ReadAll(r.Body)
	if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	// try to update...
	err = s.mdb.Update(lockId, key, memdb.Value(string(body)), release)
	if err == memdb.ErrKeyNotFound {
		w.WriteHeader(http.StatusNotFound)
		return

	} else if err == memdb.ErrLockIdNotFound {
		w.WriteHeader(http.StatusUnauthorized)
		return

	} else if err != nil {
		w.WriteHeader(http.StatusInternalServerError)
		return
	}

	w.WriteHeader(http.StatusNoContent)
}
コード例 #2
0
ファイル: server_test.go プロジェクト: plar/memdb
func TestRestServerGetKeyLock(t *testing.T) {

	server := NewRestServer()

	recorder := httptest.NewRecorder()

	// put new value
	req, err := http.NewRequest("PUT", "http://memdb.devel/values/key0", strings.NewReader("body"))
	assert.Nil(t, err)
	server.Router().ServeHTTP(recorder, req)

	jsonResponse := &LockResponse{}
	err = json.Unmarshal(recorder.Body.Bytes(), &jsonResponse)

	go func() {
		// simulate job
		time.Sleep(time.Duration(1000) * time.Millisecond)
		server.mdb.Release(memdb.LockID(jsonResponse.LockId))
	}()

	// put other value
	req2, err2 := http.NewRequest("POST", "http://rest.devel/reservations/key0", strings.NewReader(""))
	assert.Nil(t, err2)

	recorder2 := httptest.NewRecorder()
	server.Router().ServeHTTP(recorder2, req2)
	assert.Equal(t, http.StatusOK, recorder2.Code)

	jsonLockValueResponse := &LockValueResponse{}

	// //fmt.Printf("Body: %s\n", recorder.Body.String())

	err3 := json.Unmarshal(recorder2.Body.Bytes(), &jsonLockValueResponse)
	assert.NoError(t, err3)

	assert.Equal(t, "2", jsonLockValueResponse.LockId)
	assert.Equal(t, "body", jsonLockValueResponse.Value)
}