OSDN Git Service

list-addresses sort addressResp by create index
authoroysheng <oysheng@bytom.io>
Wed, 30 May 2018 09:09:52 +0000 (17:09 +0800)
committeroysheng <oysheng@bytom.io>
Wed, 30 May 2018 09:09:52 +0000 (17:09 +0800)
api/accounts.go

index 87b8364..61ec5bc 100644 (file)
@@ -2,6 +2,7 @@ package api
 
 import (
        "context"
+       "sort"
 
        log "github.com/sirupsen/logrus"
 
@@ -29,7 +30,7 @@ func (a *API) createAccount(ctx context.Context, ins struct {
        return NewSuccessResponse(annotatedAccount)
 }
 
-// AccountInfo
+// AccountInfo is request struct for deleteAccount
 type AccountInfo struct {
        Info string `json:"account_info"`
 }
@@ -86,6 +87,18 @@ type addressResp struct {
        Change       bool   `json:"change"`
 }
 
+type addressRespIndex struct {
+       KeyIndex    uint64
+       AddressResp addressResp
+}
+
+// SortByIndex implements sort.Interface for addressRespIndex slices
+type SortByIndex []addressRespIndex
+
+func (a SortByIndex) Len() int           { return len(a) }
+func (a SortByIndex) Swap(i, j int)      { a[i], a[j] = a[j], a[i] }
+func (a SortByIndex) Less(i, j int) bool { return a[i].KeyIndex < a[j].KeyIndex }
+
 func (a *API) listAddresses(ctx context.Context, ins struct {
        AccountID    string `json:"account_id"`
        AccountAlias string `json:"account_alias"`
@@ -111,17 +124,30 @@ func (a *API) listAddresses(ctx context.Context, ins struct {
                return NewErrorResponse(err)
        }
 
-       addresses := []*addressResp{}
+       addressRespIndexes := []addressRespIndex{}
        for _, cp := range cps {
                if cp.Address == "" || cp.AccountID != target.ID {
                        continue
                }
-               addresses = append(addresses, &addressResp{
-                       AccountAlias: target.Alias,
-                       AccountID:    cp.AccountID,
-                       Address:      cp.Address,
-                       Change:       cp.Change,
-               })
+
+               addressIndex := addressRespIndex{
+                       KeyIndex: cp.KeyIndex,
+                       AddressResp: addressResp{
+                               AccountAlias: target.Alias,
+                               AccountID:    cp.AccountID,
+                               Address:      cp.Address,
+                               Change:       cp.Change,
+                       },
+               }
+               addressRespIndexes = append(addressRespIndexes, addressIndex)
+       }
+
+       // sort AddressResp by KeyIndex
+       addresses := []addressResp{}
+       sort.Sort(SortByIndex(addressRespIndexes))
+       for _, addr := range addressRespIndexes {
+               addresses = append(addresses, addr.AddressResp)
        }
+
        return NewSuccessResponse(addresses)
 }