index_create.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384
  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. package http
  15. import (
  16. "encoding/json"
  17. "fmt"
  18. "io/ioutil"
  19. "net/http"
  20. "os"
  21. "github.com/blevesearch/bleve"
  22. )
  23. type CreateIndexHandler struct {
  24. basePath string
  25. IndexNameLookup varLookupFunc
  26. }
  27. func NewCreateIndexHandler(basePath string) *CreateIndexHandler {
  28. return &CreateIndexHandler{
  29. basePath: basePath,
  30. }
  31. }
  32. func (h *CreateIndexHandler) ServeHTTP(w http.ResponseWriter, req *http.Request) {
  33. // find the name of the index to create
  34. var indexName string
  35. if h.IndexNameLookup != nil {
  36. indexName = h.IndexNameLookup(req)
  37. }
  38. if indexName == "" {
  39. showError(w, req, "index name is required", 400)
  40. return
  41. }
  42. indexMapping := bleve.NewIndexMapping()
  43. // read the request body
  44. requestBody, err := ioutil.ReadAll(req.Body)
  45. if err != nil {
  46. showError(w, req, fmt.Sprintf("error reading request body: %v", err), 400)
  47. return
  48. }
  49. // interpret request body as index mapping
  50. if len(requestBody) > 0 {
  51. err := json.Unmarshal(requestBody, &indexMapping)
  52. if err != nil {
  53. showError(w, req, fmt.Sprintf("error parsing index mapping: %v", err), 400)
  54. return
  55. }
  56. }
  57. newIndex, err := bleve.New(h.indexPath(indexName), indexMapping)
  58. if err != nil {
  59. showError(w, req, fmt.Sprintf("error creating index: %v", err), 500)
  60. return
  61. }
  62. newIndex.SetName(indexName)
  63. RegisterIndexName(indexName, newIndex)
  64. rv := struct {
  65. Status string `json:"status"`
  66. }{
  67. Status: "ok",
  68. }
  69. mustEncode(w, rv)
  70. }
  71. func (h *CreateIndexHandler) indexPath(name string) string {
  72. return h.basePath + string(os.PathSeparator) + name
  73. }