request.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101
  1. package common
  2. import (
  3. "fmt"
  4. "log"
  5. "time"
  6. "github.com/denverdino/aliyungo/util"
  7. )
  8. // Constants for Aliyun API requests
  9. const (
  10. SignatureVersion = "1.0"
  11. SignatureMethod = "HMAC-SHA1"
  12. JSONResponseFormat = "JSON"
  13. XMLResponseFormat = "XML"
  14. ECSRequestMethod = "GET"
  15. )
  16. type Request struct {
  17. Format string
  18. Version string
  19. AccessKeyId string
  20. Signature string
  21. SignatureMethod string
  22. Timestamp util.ISO6801Time
  23. SignatureVersion string
  24. SignatureNonce string
  25. ResourceOwnerAccount string
  26. Action string
  27. }
  28. func (request *Request) init(version string, action string, AccessKeyId string) {
  29. request.Format = JSONResponseFormat
  30. request.Timestamp = util.NewISO6801Time(time.Now().UTC())
  31. request.Version = version
  32. request.SignatureVersion = SignatureVersion
  33. request.SignatureMethod = SignatureMethod
  34. request.SignatureNonce = util.CreateRandomString()
  35. request.Action = action
  36. request.AccessKeyId = AccessKeyId
  37. }
  38. type Response struct {
  39. RequestId string
  40. }
  41. type ErrorResponse struct {
  42. Response
  43. HostId string
  44. Code string
  45. Message string
  46. }
  47. // An Error represents a custom error for Aliyun API failure response
  48. type Error struct {
  49. ErrorResponse
  50. StatusCode int //Status Code of HTTP Response
  51. }
  52. func (e *Error) Error() string {
  53. return fmt.Sprintf("Aliyun API Error: RequestId: %s Status Code: %d Code: %s Message: %s", e.RequestId, e.StatusCode, e.Code, e.Message)
  54. }
  55. type Pagination struct {
  56. PageNumber int
  57. PageSize int
  58. }
  59. func (p *Pagination) SetPageSize(size int) {
  60. p.PageSize = size
  61. }
  62. func (p *Pagination) Validate() {
  63. if p.PageNumber < 0 {
  64. log.Printf("Invalid PageNumber: %d", p.PageNumber)
  65. p.PageNumber = 1
  66. }
  67. if p.PageSize < 0 {
  68. log.Printf("Invalid PageSize: %d", p.PageSize)
  69. p.PageSize = 10
  70. } else if p.PageSize > 50 {
  71. log.Printf("Invalid PageSize: %d", p.PageSize)
  72. p.PageSize = 50
  73. }
  74. }
  75. // A PaginationResponse represents a response with pagination information
  76. type PaginationResult struct {
  77. TotalCount int
  78. PageNumber int
  79. PageSize int
  80. }
  81. // NextPage gets the next page of the result set
  82. func (r *PaginationResult) NextPage() *Pagination {
  83. if r.PageNumber*r.PageSize >= r.TotalCount {
  84. return nil
  85. }
  86. return &Pagination{PageNumber: r.PageNumber + 1, PageSize: r.PageSize}
  87. }