index_exists.go 1.2 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657
  1. // Copyright 2012-2014 Oliver Eilhard. All rights reserved.
  2. // Use of this source code is governed by a MIT-license.
  3. // See http://olivere.mit-license.org/license.txt for details.
  4. package elastic
  5. import (
  6. "fmt"
  7. "net/http"
  8. "github.com/olivere/elastic/uritemplates"
  9. )
  10. type IndexExistsService struct {
  11. client *Client
  12. index string
  13. }
  14. func NewIndexExistsService(client *Client) *IndexExistsService {
  15. builder := &IndexExistsService{
  16. client: client,
  17. }
  18. return builder
  19. }
  20. func (b *IndexExistsService) Index(index string) *IndexExistsService {
  21. b.index = index
  22. return b
  23. }
  24. func (b *IndexExistsService) Do() (bool, error) {
  25. // Build url
  26. urls, err := uritemplates.Expand("/{index}", map[string]string{
  27. "index": b.index,
  28. })
  29. if err != nil {
  30. return false, err
  31. }
  32. // Set up a new request
  33. req, err := b.client.NewRequest("HEAD", urls)
  34. if err != nil {
  35. return false, err
  36. }
  37. // Get response
  38. res, err := b.client.c.Do((*http.Request)(req))
  39. if err != nil {
  40. return false, err
  41. }
  42. if res.StatusCode == 200 {
  43. return true, nil
  44. } else if res.StatusCode == 404 {
  45. return false, nil
  46. }
  47. return false, fmt.Errorf("elastic: got HTTP code %d when it should have been either 200 or 404", res.StatusCode)
  48. }