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.

request.go 3.4KB

  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 <https://github.com/miniflux/miniflux-go>"
  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. }
  36. func (r *request) Get(path string) (io.ReadCloser, error) {
  37. return r.execute(http.MethodGet, path, nil)
  38. }
  39. func (r *request) Post(path string, data interface{}) (io.ReadCloser, error) {
  40. return r.execute(http.MethodPost, path, data)
  41. }
  42. func (r *request) PostFile(path string, f io.ReadCloser) (io.ReadCloser, error) {
  43. return r.execute(http.MethodPost, path, f)
  44. }
  45. func (r *request) Put(path string, data interface{}) (io.ReadCloser, error) {
  46. return r.execute(http.MethodPut, path, data)
  47. }
  48. func (r *request) Delete(path string) (io.ReadCloser, error) {
  49. return r.execute(http.MethodDelete, path, nil)
  50. }
  51. func (r *request) execute(method, path string, data interface{}) (io.ReadCloser, error) {
  52. if r.endpoint[len(r.endpoint)-1:] == "/" {
  53. r.endpoint = r.endpoint[:len(r.endpoint)-1]
  54. }
  55. u, err := url.Parse(r.endpoint + path)
  56. if err != nil {
  57. return nil, err
  58. }
  59. request := &http.Request{
  60. URL: u,
  61. Method: method,
  62. Header: r.buildHeaders(),
  63. }
  64. request.SetBasicAuth(r.username, r.password)
  65. if data != nil {
  66. switch data.(type) {
  67. case io.ReadCloser:
  68. request.Body = data.(io.ReadCloser)
  69. default:
  70. request.Body = ioutil.NopCloser(bytes.NewBuffer(r.toJSON(data)))
  71. }
  72. }
  73. client := r.buildClient()
  74. response, err := client.Do(request)
  75. if err != nil {
  76. return nil, err
  77. }
  78. switch response.StatusCode {
  79. case http.StatusUnauthorized:
  80. return nil, ErrNotAuthorized
  81. case http.StatusForbidden:
  82. return nil, ErrForbidden
  83. case http.StatusInternalServerError:
  84. return nil, ErrServerError
  85. case http.StatusNotFound:
  86. return nil, ErrNotFound
  87. case http.StatusBadRequest:
  88. defer response.Body.Close()
  89. var resp errorResponse
  90. decoder := json.NewDecoder(response.Body)
  91. if err := decoder.Decode(&resp); err != nil {
  92. return nil, fmt.Errorf("miniflux: bad request error (%v)", err)
  93. }
  94. return nil, fmt.Errorf("miniflux: bad request (%s)", resp.ErrorMessage)
  95. }
  96. if response.StatusCode > 400 {
  97. return nil, fmt.Errorf("miniflux: status code=%d", response.StatusCode)
  98. }
  99. return response.Body, nil
  100. }
  101. func (r *request) buildClient() http.Client {
  102. return http.Client{
  103. Timeout: time.Duration(defaultTimeout * time.Second),
  104. }
  105. }
  106. func (r *request) buildHeaders() http.Header {
  107. headers := make(http.Header)
  108. headers.Add("User-Agent", userAgent)
  109. headers.Add("Content-Type", "application/json")
  110. headers.Add("Accept", "application/json")
  111. return headers
  112. }
  113. func (r *request) toJSON(v interface{}) []byte {
  114. b, err := json.Marshal(v)
  115. if err != nil {
  116. log.Println("Unable to convert interface to JSON:", err)
  117. return []byte("")
  118. }
  119. return b
  120. }