1
// Copyright (c) 2014 Couchbase, Inc.
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
7
// http://www.apache.org/licenses/LICENSE-2.0
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.
24
type DocIndexHandler struct {
25
defaultIndexName string
26
IndexNameLookup varLookupFunc
27
DocIDLookup varLookupFunc
30
func NewDocIndexHandler(defaultIndexName string) *DocIndexHandler {
31
return &DocIndexHandler{
32
defaultIndexName: defaultIndexName,
36
func (h *DocIndexHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
38
// find the index to operate on
40
if h.IndexNameLookup != nil {
41
indexName = h.IndexNameLookup(req)
44
indexName = h.defaultIndexName
46
index := IndexByName(indexName)
48
showError(w, req, fmt.Sprintf("no such index '%s'", indexName), 404)
54
if h.DocIDLookup != nil {
55
docID = h.DocIDLookup(req)
58
showError(w, req, "document id cannot be empty", 400)
62
// read the request body
63
requestBody, err := ioutil.ReadAll(req.Body)
65
showError(w, req, fmt.Sprintf("error reading request body: %v", err), 400)
69
// parse request body as json
71
err = json.Unmarshal(requestBody, &doc)
73
showError(w, req, fmt.Sprintf("error parsing request body as JSON: %v", err), 400)
77
err = index.Index(docID, doc)
79
showError(w, req, fmt.Sprintf("error indexing document '%s': %v", docID, err), 500)
84
Status string `json:"status"`