You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.
 
 
 

114 lines
2.3 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. // Auth username
  36. AuthUsername string
  37. // Auth password
  38. AuthPassword string
  39. }
  40. // URL builds a URL for a Request
  41. func (req *Request) URL() *url.URL {
  42. var path string
  43. if len(req.IndexList) > 0 {
  44. path = "/" + strings.Join(req.IndexList, ",")
  45. }
  46. if len(req.TypeList) > 0 {
  47. path += "/" + strings.Join(req.TypeList, ",")
  48. }
  49. // XXX : for indexing documents using the normal (non bulk) API
  50. if len(req.ID) > 0 {
  51. path += "/" + req.ID
  52. }
  53. path += "/" + req.API
  54. u := url.URL{
  55. //Scheme: "http",
  56. //Host: fmt.Sprintf("%s:%s", req.Conn.Host, req.Conn.Port),
  57. Path: path,
  58. RawQuery: req.ExtraArgs.Encode(),
  59. }
  60. return &u
  61. }
  62. // Request generates an http.Request based on the contents of the Request struct
  63. func (req *Request) Request() (*http.Request, error) {
  64. postData := []byte{}
  65. // XXX : refactor this
  66. if len(req.Body) > 0 {
  67. postData = req.Body
  68. } else if req.API == "_bulk" {
  69. postData = req.BulkData
  70. } else if req.Query != nil {
  71. b, err := json.Marshal(req.Query)
  72. if err != nil {
  73. return nil, err
  74. }
  75. postData = b
  76. }
  77. newReq, err := http.NewRequest(req.Method, "", nil)
  78. if err != nil {
  79. return nil, err
  80. }
  81. newReq.URL = req.URL()
  82. newReq.Body = ioutil.NopCloser(bytes.NewReader(postData))
  83. newReq.ContentLength = int64(len(postData))
  84. if req.Method == "POST" || req.Method == "PUT" {
  85. newReq.Header.Set("Content-Type", "application/json")
  86. }
  87. return newReq, nil
  88. }
  89. var _ Requester = (*Request)(nil)