gogs.go 2.0 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990
  1. // Copyright 2014 The Gogs Authors. All rights reserved.
  2. // Use of this source code is governed by a MIT-style
  3. // license that can be found in the LICENSE file.
  4. package gogs
  5. import (
  6. "encoding/json"
  7. "errors"
  8. "io"
  9. "io/ioutil"
  10. "net/http"
  11. "strings"
  12. )
  13. func Version() string {
  14. return "0.13.0"
  15. }
  16. // Client represents a Gogs API client.
  17. type Client struct {
  18. url string
  19. accessToken string
  20. client *http.Client
  21. }
  22. // NewClient initializes and returns an API client.
  23. func NewClient(url, token string) *Client {
  24. return &Client{
  25. url: strings.TrimSuffix(url, "/"),
  26. accessToken: token,
  27. client: &http.Client{},
  28. }
  29. }
  30. // SetHTTPClient replaces default http.Client with user given one.
  31. func (c *Client) SetHTTPClient(client *http.Client) {
  32. c.client = client
  33. }
  34. func (c *Client) doRequest(method, path string, header http.Header, body io.Reader) (*http.Response, error) {
  35. req, err := http.NewRequest(method, c.url+"/api/v1"+path, body)
  36. if err != nil {
  37. return nil, err
  38. }
  39. req.Header.Set("Authorization", "token "+c.accessToken)
  40. for k, v := range header {
  41. req.Header[k] = v
  42. }
  43. return c.client.Do(req)
  44. }
  45. func (c *Client) getResponse(method, path string, header http.Header, body io.Reader) ([]byte, error) {
  46. resp, err := c.doRequest(method, path, header, body)
  47. if err != nil {
  48. return nil, err
  49. }
  50. defer resp.Body.Close()
  51. data, err := ioutil.ReadAll(resp.Body)
  52. if err != nil {
  53. return nil, err
  54. }
  55. switch resp.StatusCode {
  56. case 403:
  57. return nil, errors.New("403 Forbidden")
  58. case 404:
  59. return nil, errors.New("404 Not Found")
  60. }
  61. if resp.StatusCode/100 != 2 {
  62. errMap := make(map[string]interface{})
  63. if err = json.Unmarshal(data, &errMap); err != nil {
  64. return nil, err
  65. }
  66. return nil, errors.New(errMap["message"].(string))
  67. }
  68. return data, nil
  69. }
  70. func (c *Client) getParsedResponse(method, path string, header http.Header, body io.Reader, obj interface{}) error {
  71. data, err := c.getResponse(method, path, header, body)
  72. if err != nil {
  73. return err
  74. }
  75. return json.Unmarshal(data, obj)
  76. }