request.go 3.7 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161
  1. // Copyright 2018 Frédéric Guillot. All rights reserved.
  2. // Use of this source code is governed by the Apache 2.0
  3. // license that can be found in the LICENSE file.
  4. package client // import "miniflux.app/client"
  5. import (
  6. "bytes"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "io"
  11. "io/ioutil"
  12. "log"
  13. "net/http"
  14. "net/url"
  15. "time"
  16. )
  17. const (
  18. userAgent = "Miniflux Client Library"
  19. defaultTimeout = 80
  20. )
  21. // List of exposed errors.
  22. var (
  23. ErrNotAuthorized = errors.New("miniflux: unauthorized (bad credentials)")
  24. ErrForbidden = errors.New("miniflux: access forbidden")
  25. ErrServerError = errors.New("miniflux: internal server error")
  26. ErrNotFound = errors.New("miniflux: resource not found")
  27. )
  28. type errorResponse struct {
  29. ErrorMessage string `json:"error_message"`
  30. }
  31. type request struct {
  32. endpoint string
  33. username string
  34. password string
  35. apiKey string
  36. }
  37. func (r *request) Get(path string) (io.ReadCloser, error) {
  38. return r.execute(http.MethodGet, path, nil)
  39. }
  40. func (r *request) Post(path string, data interface{}) (io.ReadCloser, error) {
  41. return r.execute(http.MethodPost, path, data)
  42. }
  43. func (r *request) PostFile(path string, f io.ReadCloser) (io.ReadCloser, error) {
  44. return r.execute(http.MethodPost, path, f)
  45. }
  46. func (r *request) Put(path string, data interface{}) (io.ReadCloser, error) {
  47. return r.execute(http.MethodPut, path, data)
  48. }
  49. func (r *request) Delete(path string) error {
  50. _, err := r.execute(http.MethodDelete, path, nil)
  51. return err
  52. }
  53. func (r *request) execute(method, path string, data interface{}) (io.ReadCloser, error) {
  54. if r.endpoint[len(r.endpoint)-1:] == "/" {
  55. r.endpoint = r.endpoint[:len(r.endpoint)-1]
  56. }
  57. u, err := url.Parse(r.endpoint + path)
  58. if err != nil {
  59. return nil, err
  60. }
  61. request := &http.Request{
  62. URL: u,
  63. Method: method,
  64. Header: r.buildHeaders(),
  65. }
  66. if r.username != "" && r.password != "" {
  67. request.SetBasicAuth(r.username, r.password)
  68. }
  69. if data != nil {
  70. switch data.(type) {
  71. case io.ReadCloser:
  72. request.Body = data.(io.ReadCloser)
  73. default:
  74. request.Body = ioutil.NopCloser(bytes.NewBuffer(r.toJSON(data)))
  75. }
  76. }
  77. client := r.buildClient()
  78. response, err := client.Do(request)
  79. if err != nil {
  80. return nil, err
  81. }
  82. switch response.StatusCode {
  83. case http.StatusUnauthorized:
  84. response.Body.Close()
  85. return nil, ErrNotAuthorized
  86. case http.StatusForbidden:
  87. response.Body.Close()
  88. return nil, ErrForbidden
  89. case http.StatusInternalServerError:
  90. response.Body.Close()
  91. return nil, ErrServerError
  92. case http.StatusNotFound:
  93. response.Body.Close()
  94. return nil, ErrNotFound
  95. case http.StatusNoContent:
  96. response.Body.Close()
  97. return nil, nil
  98. case http.StatusBadRequest:
  99. defer response.Body.Close()
  100. var resp errorResponse
  101. decoder := json.NewDecoder(response.Body)
  102. if err := decoder.Decode(&resp); err != nil {
  103. return nil, fmt.Errorf("miniflux: bad request error (%v)", err)
  104. }
  105. return nil, fmt.Errorf("miniflux: bad request (%s)", resp.ErrorMessage)
  106. }
  107. if response.StatusCode > 400 {
  108. response.Body.Close()
  109. return nil, fmt.Errorf("miniflux: status code=%d", response.StatusCode)
  110. }
  111. return response.Body, nil
  112. }
  113. func (r *request) buildClient() http.Client {
  114. return http.Client{
  115. Timeout: time.Duration(defaultTimeout * time.Second),
  116. }
  117. }
  118. func (r *request) buildHeaders() http.Header {
  119. headers := make(http.Header)
  120. headers.Add("User-Agent", userAgent)
  121. headers.Add("Content-Type", "application/json")
  122. headers.Add("Accept", "application/json")
  123. if r.apiKey != "" {
  124. headers.Add("X-Auth-Token", r.apiKey)
  125. }
  126. return headers
  127. }
  128. func (r *request) toJSON(v interface{}) []byte {
  129. b, err := json.Marshal(v)
  130. if err != nil {
  131. log.Println("Unable to convert interface to JSON:", err)
  132. return []byte("")
  133. }
  134. return b
  135. }