1//  Copyright (c) 2014 Couchbase, Inc.
2//
3// Licensed under the Apache License, Version 2.0 (the "License");
4// you may not use this file except in compliance with the License.
5// You may obtain a copy of the License at
6//
7// 		http://www.apache.org/licenses/LICENSE-2.0
8//
9// Unless required by applicable law or agreed to in writing, software
10// distributed under the License is distributed on an "AS IS" BASIS,
11// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12// See the License for the specific language governing permissions and
13// limitations under the License.
14
15package http
16
17import (
18	"fmt"
19	"net/http"
20)
21
22type DocDeleteHandler struct {
23	defaultIndexName string
24	IndexNameLookup  varLookupFunc
25	DocIDLookup      varLookupFunc
26}
27
28func NewDocDeleteHandler(defaultIndexName string) *DocDeleteHandler {
29	return &DocDeleteHandler{
30		defaultIndexName: defaultIndexName,
31	}
32}
33
34func (h *DocDeleteHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
35
36	// find the index to operate on
37	var indexName string
38	if h.IndexNameLookup != nil {
39		indexName = h.IndexNameLookup(req)
40	}
41	if indexName == "" {
42		indexName = h.defaultIndexName
43	}
44	index := IndexByName(indexName)
45	if index == nil {
46		showError(w, req, fmt.Sprintf("no such index '%s'", indexName), 404)
47		return
48	}
49
50	// find the doc id
51	var docID string
52	if h.DocIDLookup != nil {
53		docID = h.DocIDLookup(req)
54	}
55	if docID == "" {
56		showError(w, req, "document id cannot be empty", 400)
57		return
58	}
59
60	err := index.Delete(docID)
61	if err != nil {
62		showError(w, req, fmt.Sprintf("error deleting document '%s': %v", docID, err), 500)
63		return
64	}
65
66	rv := struct {
67		Status string `json:"status"`
68	}{
69		Status: "ok",
70	}
71	mustEncode(w, rv)
72}
73