client.go 2.1 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596
  1. // Copyright (C) 2019 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package main
  7. import (
  8. "bytes"
  9. "context"
  10. "crypto/tls"
  11. "errors"
  12. "fmt"
  13. "net"
  14. "net/http"
  15. "strings"
  16. "github.com/syncthing/syncthing/lib/config"
  17. )
  18. type APIClient struct {
  19. http.Client
  20. cfg config.GUIConfiguration
  21. apikey string
  22. }
  23. func getClient(cfg config.GUIConfiguration) *APIClient {
  24. httpClient := http.Client{
  25. Transport: &http.Transport{
  26. TLSClientConfig: &tls.Config{
  27. InsecureSkipVerify: true,
  28. },
  29. DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
  30. return net.Dial(cfg.Network(), cfg.Address())
  31. },
  32. },
  33. }
  34. return &APIClient{
  35. Client: httpClient,
  36. cfg: cfg,
  37. apikey: cfg.APIKey,
  38. }
  39. }
  40. func (c *APIClient) Endpoint() string {
  41. if c.cfg.Network() == "unix" {
  42. return "http://unix/"
  43. }
  44. url := c.cfg.URL()
  45. if !strings.HasSuffix(url, "/") {
  46. url += "/"
  47. }
  48. return url
  49. }
  50. func (c *APIClient) Do(req *http.Request) (*http.Response, error) {
  51. req.Header.Set("X-API-Key", c.apikey)
  52. resp, err := c.Client.Do(req)
  53. if err != nil {
  54. return nil, err
  55. }
  56. return resp, checkResponse(resp)
  57. }
  58. func (c *APIClient) Get(url string) (*http.Response, error) {
  59. request, err := http.NewRequest("GET", c.Endpoint()+"rest/"+url, nil)
  60. if err != nil {
  61. return nil, err
  62. }
  63. return c.Do(request)
  64. }
  65. func (c *APIClient) Post(url, body string) (*http.Response, error) {
  66. request, err := http.NewRequest("POST", c.Endpoint()+"rest/"+url, bytes.NewBufferString(body))
  67. if err != nil {
  68. return nil, err
  69. }
  70. return c.Do(request)
  71. }
  72. func checkResponse(response *http.Response) error {
  73. if response.StatusCode == 404 {
  74. return errors.New("invalid endpoint or API call")
  75. } else if response.StatusCode == 403 {
  76. return errors.New("invalid API key")
  77. } else if response.StatusCode != 200 {
  78. data, err := responseToBArray(response)
  79. if err != nil {
  80. return err
  81. }
  82. body := strings.TrimSpace(string(data))
  83. return fmt.Errorf("unexpected HTTP status returned: %s\n%s", response.Status, body)
  84. }
  85. return nil
  86. }