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 DocCountHandler struct {
23	defaultIndexName string
24	IndexNameLookup  varLookupFunc
25}
26
27func NewDocCountHandler(defaultIndexName string) *DocCountHandler {
28	return &DocCountHandler{
29		defaultIndexName: defaultIndexName,
30	}
31}
32
33func (h *DocCountHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
34	// find the index to operate on
35	var indexName string
36	if h.IndexNameLookup != nil {
37		indexName = h.IndexNameLookup(req)
38	}
39	if indexName == "" {
40		indexName = h.defaultIndexName
41	}
42	index := IndexByName(indexName)
43	if index == nil {
44		showError(w, req, fmt.Sprintf("no such index '%s'", indexName), 404)
45		return
46	}
47
48	docCount, err := index.DocCount()
49	if err != nil {
50		showError(w, req, fmt.Sprintf("error counting docs: %v", err), 500)
51		return
52	}
53	rv := struct {
54		Status string `json:"status"`
55		Count  uint64 `json:"count"`
56	}{
57		Status: "ok",
58		Count:  docCount,
59	}
60	mustEncode(w, rv)
61}
62