gogs.go 2.0 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091
  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.12.12"
  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 a 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. }