Вы не можете выбрать более 25 тем Темы должны начинаться с буквы или цифры, могут содержать дефисы(-) и должны содержать не более 35 символов.

108 строки
2.2 KiB

  1. package goes
  2. import (
  3. "bytes"
  4. "encoding/json"
  5. "io/ioutil"
  6. "net/http"
  7. "net/url"
  8. "strings"
  9. )
  10. // Requester implements Request which builds an HTTP request for Elasticsearch
  11. type Requester interface {
  12. // Request should set the URL and Body (if needed). The host of the URL will be overwritten by the client.
  13. Request() (*http.Request, error)
  14. }
  15. // Request holds a single request to elasticsearch
  16. type Request struct {
  17. // A search query
  18. Query interface{}
  19. // Which index to search into
  20. IndexList []string
  21. // Which type to search into
  22. TypeList []string
  23. // HTTP Method to user (GET, POST ...)
  24. Method string
  25. // Which api keyword (_search, _bulk, etc) to use
  26. API string
  27. // Bulk data
  28. BulkData []byte
  29. // Request body
  30. Body []byte
  31. // A list of extra URL arguments
  32. ExtraArgs url.Values
  33. // Used for the id field when indexing a document
  34. ID string
  35. }
  36. // URL builds a URL for a Request
  37. func (req *Request) URL() *url.URL {
  38. var path string
  39. if len(req.IndexList) > 0 {
  40. path = "/" + strings.Join(req.IndexList, ",")
  41. }
  42. if len(req.TypeList) > 0 {
  43. path += "/" + strings.Join(req.TypeList, ",")
  44. }
  45. // XXX : for indexing documents using the normal (non bulk) API
  46. if len(req.ID) > 0 {
  47. path += "/" + req.ID
  48. }
  49. path += "/" + req.API
  50. u := url.URL{
  51. //Scheme: "http",
  52. //Host: fmt.Sprintf("%s:%s", req.Conn.Host, req.Conn.Port),
  53. Path: path,
  54. RawQuery: req.ExtraArgs.Encode(),
  55. }
  56. return &u
  57. }
  58. // Request generates an http.Request based on the contents of the Request struct
  59. func (req *Request) Request() (*http.Request, error) {
  60. postData := []byte{}
  61. // XXX : refactor this
  62. if len(req.Body) > 0 {
  63. postData = req.Body
  64. } else if req.API == "_bulk" {
  65. postData = req.BulkData
  66. } else if req.Query != nil {
  67. b, err := json.Marshal(req.Query)
  68. if err != nil {
  69. return nil, err
  70. }
  71. postData = b
  72. }
  73. newReq, err := http.NewRequest(req.Method, "", nil)
  74. if err != nil {
  75. return nil, err
  76. }
  77. newReq.URL = req.URL()
  78. newReq.Body = ioutil.NopCloser(bytes.NewReader(postData))
  79. newReq.ContentLength = int64(len(postData))
  80. if req.Method == "POST" || req.Method == "PUT" {
  81. newReq.Header.Set("Content-Type", "application/json")
  82. }
  83. return newReq, nil
  84. }
  85. var _ Requester = (*Request)(nil)