client.go 2.1 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495
  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. "fmt"
  12. "net"
  13. "net/http"
  14. "strings"
  15. "github.com/syncthing/syncthing/lib/config"
  16. )
  17. type APIClient struct {
  18. http.Client
  19. cfg config.GUIConfiguration
  20. apikey string
  21. }
  22. func getClient(cfg config.GUIConfiguration) *APIClient {
  23. httpClient := http.Client{
  24. Transport: &http.Transport{
  25. TLSClientConfig: &tls.Config{
  26. InsecureSkipVerify: true,
  27. },
  28. DialContext: func(_ context.Context, _, _ string) (net.Conn, error) {
  29. return net.Dial(cfg.Network(), cfg.Address())
  30. },
  31. },
  32. }
  33. return &APIClient{
  34. Client: httpClient,
  35. cfg: cfg,
  36. apikey: cfg.APIKey,
  37. }
  38. }
  39. func (c *APIClient) Endpoint() string {
  40. if c.cfg.Network() == "unix" {
  41. return "http://unix/"
  42. }
  43. url := c.cfg.URL()
  44. if !strings.HasSuffix(url, "/") {
  45. url += "/"
  46. }
  47. return url
  48. }
  49. func (c *APIClient) Do(req *http.Request) (*http.Response, error) {
  50. req.Header.Set("X-API-Key", c.apikey)
  51. resp, err := c.Client.Do(req)
  52. if err != nil {
  53. return nil, err
  54. }
  55. return resp, checkResponse(resp)
  56. }
  57. func (c *APIClient) Get(url string) (*http.Response, error) {
  58. request, err := http.NewRequest("GET", c.Endpoint()+"rest/"+url, nil)
  59. if err != nil {
  60. return nil, err
  61. }
  62. return c.Do(request)
  63. }
  64. func (c *APIClient) Post(url, body string) (*http.Response, error) {
  65. request, err := http.NewRequest("POST", c.Endpoint()+"rest/"+url, bytes.NewBufferString(body))
  66. if err != nil {
  67. return nil, err
  68. }
  69. return c.Do(request)
  70. }
  71. func checkResponse(response *http.Response) error {
  72. if response.StatusCode == 404 {
  73. return fmt.Errorf("Invalid endpoint or API call")
  74. } else if response.StatusCode == 403 {
  75. return fmt.Errorf("Invalid API key")
  76. } else if response.StatusCode != 200 {
  77. data, err := responseToBArray(response)
  78. if err != nil {
  79. return err
  80. }
  81. body := strings.TrimSpace(string(data))
  82. return fmt.Errorf("Unexpected HTTP status returned: %s\n%s", response.Status, body)
  83. }
  84. return nil
  85. }