request.go 1.3 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859
  1. // Copyright 2012-2015 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. "bytes"
  7. "encoding/json"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "runtime"
  12. "strings"
  13. )
  14. // Elasticsearch-specific HTTP request
  15. type Request http.Request
  16. func NewRequest(method, url string) (*Request, error) {
  17. req, err := http.NewRequest(method, url, nil)
  18. if err != nil {
  19. return nil, err
  20. }
  21. req.Header.Add("User-Agent", "elastic/"+Version+" ("+runtime.GOOS+"-"+runtime.GOARCH+")")
  22. req.Header.Add("Accept", "application/json")
  23. return (*Request)(req), nil
  24. }
  25. func (r *Request) SetBodyJson(data interface{}) error {
  26. body, err := json.Marshal(data)
  27. if err != nil {
  28. return err
  29. }
  30. r.SetBody(bytes.NewReader(body))
  31. r.Header.Set("Content-Type", "application/json")
  32. return nil
  33. }
  34. func (r *Request) SetBodyString(body string) error {
  35. return r.SetBody(strings.NewReader(body))
  36. }
  37. func (r *Request) SetBody(body io.Reader) error {
  38. rc, ok := body.(io.ReadCloser)
  39. if !ok && body != nil {
  40. rc = ioutil.NopCloser(body)
  41. }
  42. r.Body = rc
  43. if body != nil {
  44. switch v := body.(type) {
  45. case *strings.Reader:
  46. r.ContentLength = int64(v.Len())
  47. case *bytes.Buffer:
  48. r.ContentLength = int64(v.Len())
  49. }
  50. }
  51. return nil
  52. }