github.com/nesv/gothub@v0.0.0-20140406181320-f0c824044d5f/gothub.go (about)

     1  package gothub
     2  
     3  import (
     4  	"bytes"
     5  	"encoding/base64"
     6  	"encoding/json"
     7  	"errors"
     8  	"fmt"
     9  	"io/ioutil"
    10  	"net/http"
    11  	"strconv"
    12  	"strings"
    13  )
    14  
    15  // The HTTP host that we will hit to use the GitHub API.
    16  const (
    17  	GitHubUrl       string = "https://api.github.com"
    18  	DefaultPageSize int    = 30
    19  	AcceptHeader    string = "application/vnd.github.beta+json"
    20  )
    21  
    22  var (
    23  	ErrRateLimitReached = errors.New("Rate limit reached")
    24  	ErrNoJSON           = errors.New("GitHub did not return a JSON response")
    25  )
    26  
    27  // The GitHub struct represents an active session to the GitHub API.
    28  type GitHub struct {
    29  	httpClient         *http.Client
    30  	Authorization      string
    31  	RateLimit          int
    32  	RateLimitRemaining int
    33  }
    34  
    35  func hashAuth(u, p string) string {
    36  	var a = fmt.Sprintf("%s:%s", u, p)
    37  	return base64.StdEncoding.EncodeToString([]byte(a))
    38  }
    39  
    40  // Use API without authentication
    41  func Guest() (*GitHub, error) {
    42  	request, err := http.NewRequest("GET", GitHubUrl, nil)
    43  	if err != nil {
    44  		return nil, err
    45  	}
    46  
    47  	client := &http.Client{}
    48  	response, err := client.Do(request)
    49  	if response.StatusCode == http.StatusOK {
    50  		ratelimit, err := strconv.Atoi(response.Header.Get("X-RateLimit-Limit"))
    51  		if err != nil {
    52  			return nil, err
    53  		}
    54  
    55  		remaining, err := strconv.Atoi(response.Header.Get("X-RateLimit-Remaining"))
    56  		if err != nil {
    57  			return nil, err
    58  		}
    59  
    60  		return &GitHub{httpClient: client, RateLimit: ratelimit, RateLimitRemaining: remaining}, nil
    61  	}
    62  
    63  	return nil, err
    64  }
    65  
    66  // Log in to GitHub using basic, username/password authentication.
    67  func BasicLogin(username, password string) (*GitHub, error) {
    68  	// Format and Base64-encode the provided username and password, in preparation for basic
    69  	// HTTP auth.
    70  	authorization := fmt.Sprintf("Basic %s", hashAuth(username, password))
    71  	request, err := http.NewRequest("GET", GitHubUrl, nil)
    72  	if err != nil {
    73  		return nil, err
    74  	}
    75  
    76  	// Set the Authorization header.
    77  	request.Header.Set("Authorization", authorization)
    78  
    79  	// Create a new HTTP client (which we will eventually provide to the GitHub struct), for
    80  	// issuing the above HTTP request, and future requests.
    81  	client := &http.Client{}
    82  	response, err := client.Do(request)
    83  	if err != nil {
    84  		return nil, err
    85  	}
    86  
    87  	if response.StatusCode == http.StatusOK {
    88  		// Yaaaaaaay!
    89  		ratelimit, err := strconv.Atoi(response.Header.Get("X-RateLimit-Limit"))
    90  		if err != nil {
    91  			return nil, err
    92  		}
    93  
    94  		remaining, err := strconv.Atoi(response.Header.Get("X-RateLimit-Remaining"))
    95  		if err != nil {
    96  			return nil, err
    97  		}
    98  
    99  		return &GitHub{httpClient: client, Authorization: authorization,
   100  			RateLimit: ratelimit, RateLimitRemaining: remaining}, nil
   101  	}
   102  
   103  	// Should we get here, the basic authentication request failed.
   104  	e := "Authorization failed with HTTP code: %d"
   105  	return nil, errors.New(fmt.Sprintf(e, response.StatusCode))
   106  }
   107  
   108  /*
   109  Calls the specified GitHub endpoint, with the provided HTTP method, and
   110  unmarshals the JSON response (if there is one) into the provided interface{} v.
   111  
   112  You can use this function to interact with a majority of the GitHub v3
   113  endpoints.
   114  */
   115  func (g *GitHub) Do(v interface{}, method string, uriParts ...string) (err error) {
   116  	if g.RateLimitRemaining == 0 {
   117  		err = ErrRateLimitReached
   118  		return
   119  	}
   120  
   121  	url := fmt.Sprintf("%s/%s", GitHubUrl, strings.Join(uriParts, "/"))
   122  
   123  	var request *http.Request
   124  	request, err = http.NewRequest(method, url, nil)
   125  	if err != nil {
   126  		return
   127  	}
   128  
   129  	request.Header.Set("Authorization", g.Authorization)
   130  	request.Header.Set("Accept", AcceptHeader)
   131  
   132  	var response *http.Response
   133  	response, err = g.httpClient.Do(request)
   134  	if err != nil {
   135  		return
   136  	}
   137  	g.updateRates(response)
   138  
   139  	switch strings.ToUpper(method) {
   140  	case "GET":
   141  		switch response.StatusCode {
   142  		case http.StatusNoContent, http.StatusOK:
   143  			if response.ContentLength == 0 && v == nil {
   144  				// All is good in the hood.
   145  				return
   146  			}
   147  		default:
   148  			err = errors.New(fmt.Sprintf("GitHub API responded with HTTP %d", response.StatusCode))
   149  			return
   150  		}
   151  	}
   152  
   153  	// If the user supplied an interface{} to unmarshal the JSON response
   154  	// body into, then do what is necessary!
   155  	if v != nil {
   156  		switch response.Header.Get("Content-Type") {
   157  		case "application/json":
   158  			fallthrough
   159  		case "application/json; charset=utf-8":
   160  			var body []byte
   161  			body, err = ioutil.ReadAll(response.Body)
   162  			if err != nil {
   163  				return
   164  			}
   165  
   166  			err = json.Unmarshal(body, v)
   167  		default:
   168  			err = ErrNoJSON
   169  		}
   170  	}
   171  
   172  	return
   173  }
   174  
   175  // Updates the call limit rates in the GitHub struct.
   176  func (g *GitHub) updateRates(r *http.Response) (err error) {
   177  	limit, err := strconv.Atoi(r.Header.Get("X-RateLimit-Limit"))
   178  	if err != nil {
   179  		return
   180  	}
   181  	g.RateLimit = limit
   182  
   183  	remaining, err := strconv.Atoi(r.Header.Get("X-RateLimit-Remaining"))
   184  	if err != nil {
   185  		return
   186  	}
   187  	g.RateLimitRemaining = remaining
   188  	return
   189  }
   190  
   191  // Calls the GitHub API and returns the raw, HTTP response body.
   192  func call(g *GitHub, method, uri string) (response *http.Response, err error) {
   193  	if g.RateLimitRemaining == 0 {
   194  		err = ErrRateLimitReached
   195  		return
   196  	}
   197  
   198  	url := fmt.Sprintf("%s%s", GitHubUrl, uri)
   199  	request, err := http.NewRequest(method, url, nil)
   200  	if err != nil {
   201  		return
   202  	}
   203  
   204  	if g.Authorization != "" {
   205  		// Use Authorization when you logged in
   206  		request.Header.Set("Authorization", g.Authorization)
   207  	}
   208  	request.Header.Set("Accept", AcceptHeader)
   209  
   210  	// Fire off the request.
   211  	response, err = g.httpClient.Do(request)
   212  	if err != nil {
   213  		return
   214  	}
   215  
   216  	// Update the call rates
   217  	g.updateRates(response)
   218  
   219  	// Check to make sure the API came back with an appropriate HTTP status
   220  	// code, depending on the request method
   221  	switch method {
   222  	case "GET":
   223  		if response.StatusCode != http.StatusOK {
   224  			e := "GitHub API responded with HTTP %d"
   225  			err = errors.New(fmt.Sprintf(e, response.StatusCode))
   226  		}
   227  
   228  	case "POST":
   229  		switch response.StatusCode {
   230  		case http.StatusCreated:
   231  			return
   232  		}
   233  
   234  	case "DELETE":
   235  		switch response.StatusCode {
   236  		case http.StatusNoContent:
   237  			return
   238  		}
   239  	}
   240  
   241  	return
   242  }
   243  
   244  // Calls the GitHub API, but will unmarshal a JSON response to the struct
   245  // provided to `rs`.
   246  func (g *GitHub) callGithubApi(method, uri string, rs interface{}) error {
   247  	response, err := call(g, method, uri)
   248  	if err != nil {
   249  		return err
   250  	}
   251  
   252  	// Check to make sure we actually got JSON back.
   253  	switch response.Header.Get("Content-Type") {
   254  	case "application/json":
   255  		fallthrough
   256  	case "application/json; charset=utf-8":
   257  		var js []byte
   258  		js, err := ioutil.ReadAll(response.Body)
   259  		if err != nil {
   260  			return err
   261  		} else {
   262  			err = json.Unmarshal(js, rs)
   263  		}
   264  	default:
   265  		err = ErrNoJSON
   266  	}
   267  
   268  	return err
   269  }
   270  
   271  type unprocessableEntityError struct {
   272  	Resource string `json:"resource"`
   273  	Field    string `json:"field"`
   274  	Code     string `json:"code"`
   275  }
   276  
   277  type unprocessableEntity struct {
   278  	Message string                     `json:"message"`
   279  	Errors  []unprocessableEntityError `json:"errors"`
   280  }
   281  
   282  // Stuffs the approriate Authorization header into place on the request, then
   283  // calls the GitHub API and udpates the API limit rates.
   284  func (g *GitHub) call(req *http.Request) (response *http.Response, err error) {
   285  	if g.RateLimitRemaining == 0 {
   286  		err = ErrRateLimitReached
   287  		return
   288  	}
   289  
   290  	req.Header.Set("Authorization", g.Authorization)
   291  
   292  	response, err = g.httpClient.Do(req)
   293  	g.updateRates(response)
   294  
   295  	// Special handling for the HTTP 422 Unprocessable Entity.
   296  	if response.StatusCode != 422 {
   297  		return
   298  	}
   299  
   300  	// Stupid "err is shadowed during return"
   301  	body, err := ioutil.ReadAll(response.Body)
   302  	var uerror error
   303  	if err == nil {
   304  		var unprocessable unprocessableEntity
   305  		err = json.Unmarshal(body, &unprocessable)
   306  		if err != nil {
   307  			return
   308  		}
   309  
   310  		e := "%s: %+v"
   311  		uerror = errors.New(fmt.Sprintf(e, unprocessable.Message,
   312  			unprocessable.Errors))
   313  	}
   314  
   315  	if uerror != nil {
   316  		err = uerror
   317  	}
   318  
   319  	return
   320  }
   321  
   322  // Makes an HTTP GET request to the specified GitHub endpoint.
   323  func (g *GitHub) httpGet(uri string, extraHeaders map[string]string) (resp *http.Response, err error) {
   324  	url := fmt.Sprintf("%s%s", GitHubUrl, uri)
   325  	request, err := http.NewRequest("GET", url, nil)
   326  	if err != nil {
   327  		return
   328  	}
   329  
   330  	if extraHeaders != nil {
   331  		for k, v := range extraHeaders {
   332  			request.Header.Set(k, v)
   333  		}
   334  	}
   335  
   336  	resp, err = g.call(request)
   337  	return
   338  }
   339  
   340  // Makes an HTTP POST request to the specified GitHub endpoint.
   341  func (g *GitHub) httpPost(uri string, extraHeaders map[string]string, content *bytes.Buffer) (resp *http.Response, err error) {
   342  	url := fmt.Sprintf("%s%s", GitHubUrl, uri)
   343  	request, err := http.NewRequest("POST", url, content)
   344  	if err != nil {
   345  		return
   346  	}
   347  
   348  	// Add (any of) the extra headers to the request
   349  	if extraHeaders != nil {
   350  		for h, v := range extraHeaders {
   351  			request.Header.Set(h, v)
   352  		}
   353  	}
   354  
   355  	// Set the Content-Type header
   356  	request.Header.Set("Content-Type", "application/json; charset=utf-8")
   357  	resp, err = g.call(request)
   358  	return
   359  }
   360  
   361  // Makes an HTTP DELETE request to the specified GitHub endpoint.
   362  func (g *GitHub) httpDelete(uri string, extraHeaders map[string]string, content *bytes.Buffer) (resp *http.Response, err error) {
   363  	url := fmt.Sprintf("%s%s", GitHubUrl, uri)
   364  	var request *http.Request
   365  	if content != nil {
   366  		request, err = http.NewRequest("DELETE", url, content)
   367  	} else {
   368  		request, err = http.NewRequest("DELETE", url, nil)
   369  	}
   370  	if err != nil {
   371  		return
   372  	}
   373  
   374  	if extraHeaders != nil {
   375  		for h, v := range extraHeaders {
   376  			request.Header.Set(h, v)
   377  		}
   378  	}
   379  
   380  	request.Header.Set("Content-Type", "application/json; charset=utf-8")
   381  	resp, err = g.call(request)
   382  	return
   383  }
   384  
   385  // Makes an HTTP PUT request.
   386  func (g *GitHub) httpPut(uri string, extraHeaders map[string]string, content *bytes.Buffer) (resp *http.Response, err error) {
   387  	url := fmt.Sprintf("%s%s", GitHubUrl, uri)
   388  	var request *http.Request
   389  	if content != nil {
   390  		request, err = http.NewRequest("PUT", url, content)
   391  	} else {
   392  		request, err = http.NewRequest("PUT", url, nil)
   393  	}
   394  	if err != nil {
   395  		return
   396  	}
   397  
   398  	if extraHeaders != nil {
   399  		for h, v := range extraHeaders {
   400  			request.Header.Set(h, v)
   401  		}
   402  	}
   403  
   404  	request.Header.Set("Content-Type", "application/json; charset=utf-8")
   405  	resp, err = g.call(request)
   406  	return
   407  }
   408  
   409  // Makes an HTTP PATCH request.
   410  func (g *GitHub) httpPatch(uri string, extraHeaders map[string]string, content *bytes.Buffer) (resp *http.Response, err error) {
   411  	url := fmt.Sprintf("%s%s", GitHubUrl, uri)
   412  	var request *http.Request
   413  	if content != nil {
   414  		request, err = http.NewRequest("PATCH", url, content)
   415  	} else {
   416  		request, err = http.NewRequest("PATCH", url, nil)
   417  	}
   418  
   419  	if err != nil {
   420  		return
   421  	}
   422  
   423  	if extraHeaders != nil {
   424  		for h, v := range extraHeaders {
   425  			request.Header.Set(h, v)
   426  		}
   427  	}
   428  
   429  	request.Header.Set("Content-Type", "application/json; charset=utf-8")
   430  	resp, err = g.call(request)
   431  	return
   432  }