| 1 |
package common |
| 2 |
|
| 3 |
import ( |
| 4 |
"fmt" |
| 5 |
"log" |
| 6 |
"time" |
| 7 |
|
| 8 |
"github.com/denverdino/aliyungo/util" |
| 9 |
) |
| 10 |
|
| 11 |
|
| 12 |
const ( |
| 13 |
SignatureVersion = "1.0" |
| 14 |
SignatureMethod = "HMAC-SHA1" |
| 15 |
JSONResponseFormat = "JSON" |
| 16 |
XMLResponseFormat = "XML" |
| 17 |
ECSRequestMethod = "GET" |
| 18 |
) |
| 19 |
|
| 20 |
type Request struct { |
| 21 |
Format string |
| 22 |
Version string |
| 23 |
RegionId Region |
| 24 |
AccessKeyId string |
| 25 |
SecurityToken string |
| 26 |
Signature string |
| 27 |
SignatureMethod string |
| 28 |
Timestamp util.ISO6801Time |
| 29 |
SignatureVersion string |
| 30 |
SignatureNonce string |
| 31 |
ResourceOwnerAccount string |
| 32 |
Action string |
| 33 |
} |
| 34 |
|
| 35 |
func (request *Request) init(version string, action string, AccessKeyId string, securityToken string, regionId Region) { |
| 36 |
request.Format = JSONResponseFormat |
| 37 |
request.Timestamp = util.NewISO6801Time(time.Now().UTC()) |
| 38 |
request.Version = version |
| 39 |
request.SignatureVersion = SignatureVersion |
| 40 |
request.SignatureMethod = SignatureMethod |
| 41 |
request.SignatureNonce = util.CreateRandomString() |
| 42 |
request.Action = action |
| 43 |
request.AccessKeyId = AccessKeyId |
| 44 |
request.SecurityToken = securityToken |
| 45 |
request.RegionId = regionId |
| 46 |
} |
| 47 |
|
| 48 |
type Response struct { |
| 49 |
RequestId string |
| 50 |
} |
| 51 |
|
| 52 |
type ErrorResponse struct { |
| 53 |
Response |
| 54 |
HostId string |
| 55 |
Code string |
| 56 |
Message string |
| 57 |
} |
| 58 |
|
| 59 |
|
| 60 |
type Error struct { |
| 61 |
ErrorResponse |
| 62 |
StatusCode int |
| 63 |
} |
| 64 |
|
| 65 |
func (e *Error) Error() string { |
| 66 |
return fmt.Sprintf("Aliyun API Error: RequestId: %s Status Code: %d Code: %s Message: %s", e.RequestId, e.StatusCode, e.Code, e.Message) |
| 67 |
} |
| 68 |
|
| 69 |
type Pagination struct { |
| 70 |
PageNumber int |
| 71 |
PageSize int |
| 72 |
} |
| 73 |
|
| 74 |
func (p *Pagination) SetPageSize(size int) { |
| 75 |
p.PageSize = size |
| 76 |
} |
| 77 |
|
| 78 |
func (p *Pagination) Validate() { |
| 79 |
if p.PageNumber < 0 { |
| 80 |
log.Printf("Invalid PageNumber: %d", p.PageNumber) |
| 81 |
p.PageNumber = 1 |
| 82 |
} |
| 83 |
if p.PageSize < 0 { |
| 84 |
log.Printf("Invalid PageSize: %d", p.PageSize) |
| 85 |
p.PageSize = 10 |
| 86 |
} else if p.PageSize > 50 { |
| 87 |
log.Printf("Invalid PageSize: %d", p.PageSize) |
| 88 |
p.PageSize = 50 |
| 89 |
} |
| 90 |
} |
| 91 |
|
| 92 |
|
| 93 |
type PaginationResult struct { |
| 94 |
TotalCount int |
| 95 |
PageNumber int |
| 96 |
PageSize int |
| 97 |
} |
| 98 |
|
| 99 |
|
| 100 |
func (r *PaginationResult) NextPage() *Pagination { |
| 101 |
if r.PageNumber*r.PageSize >= r.TotalCount { |
| 102 |
return nil |
| 103 |
} |
| 104 |
return &Pagination{PageNumber: r.PageNumber + 1, PageSize: r.PageSize} |
| 105 |
} |