method.go raw

   1  package rest
   2  
   3  // Method is a struct which is used by the client to present a HTTP method of choice
   4  // and the expected return status codes on which you can check to see if the response is correct,
   5  // thus not an error.
   6  type Method struct {
   7  	// Method is where a HTTP method like "GET" would go
   8  	Method string
   9  	// ExpectedStatusCodes are the expected status codes with which
  10  	// you can check if the response status code is correct
  11  	ExpectedStatusCodes []int
  12  }
  13  
  14  var (
  15  	// GetMethod is a wrapper with expected status codes around the HTTP "GET" method
  16  	GetMethod = Method{Method: "GET", ExpectedStatusCodes: []int{200}}
  17  	// PostMethod is a wrapper with expected status codes around the HTTP "POST" method
  18  	PostMethod = Method{Method: "POST", ExpectedStatusCodes: []int{200, 201}}
  19  	// PutMethod is a wrapper with expected status codes around the HTTP "PUT" method
  20  	PutMethod = Method{Method: "PUT", ExpectedStatusCodes: []int{204}}
  21  	// PatchMethod is a wrapper with expected status codes around the HTTP "PATCH" method
  22  	PatchMethod = Method{Method: "PATCH", ExpectedStatusCodes: []int{204}}
  23  	// DeleteMethod is a wrapper with expected status codes around the HTTP "DELETE" method
  24  	DeleteMethod = Method{Method: "DELETE", ExpectedStatusCodes: []int{204}}
  25  )
  26  
  27  // StatusCodeOK returns true when the status code is correct
  28  // This method used by the rest client to check if the given status code is correct.
  29  func (r *Method) StatusCodeOK(statusCode int) bool {
  30  	return contains(r.ExpectedStatusCodes, statusCode)
  31  }
  32  
  33  // contains is used to see if a certain value is part of an array
  34  func contains(haystack []int, needle int) bool {
  35  	for _, a := range haystack {
  36  		if a == needle {
  37  			return true
  38  		}
  39  	}
  40  	return false
  41  }
  42