最近通过gitlab去获取服务的版本的时候顺序是乱的, 导致运维平台获取最新的10个版本,不是最新的.
元素局大概是这样.
[
[
{
"name":"v0.9.4",
"commit":{
"committed_date":"2020-02-28T20:14:27+08:00"
}
},
{
"name":"v0.11.5",
"commit":{
"committed_date":"2020-07-01T17:15:53+08:00"
}
},
{
"name":"v0.14.6",
"commit":{
"committed_date":"2020-08-02T18:20:22+08:00"
}
},
{
"name":"v0.9.7",
"commit":{
"committed_date":"2020-03-25T17:04:17+08:00"
}
}
]
我是是按照committed_date 排序, 要想用go 自带sort 排序就得实现sort 接口, 接口规范如下
type Interface interface {
// Len is the number of elements in the collection.
Len() int
// Less reports whether the element with
// index i should sort before the element with index j.
Less(i, j int) bool
// Swap swaps the elements with indexes i and j.
Swap(i, j int)
}
排序的完整代码如下:
package main
import (
"fmt"
"github.com/json-iterator/go"
"log"
"sort"
"time"
)
func main() {
var tag Tags
err := jsoniter.Unmarshal([]byte(sourceDatas), &tag)
if err != nil {
log.Fatal(err.Error())
return
}
sort.Sort(tag)
fmt.Printf("排序后的的数据 %s", tag)
}
type Tag struct {
Name string `json:"name"`
Commit struct {
CommittedDate time.Time `json:"committed_date"`
} `json:"commit"`
}
// 需要排序的json
var sourceDatas = `[
{
"name":"v0.9.4",
"commit":{
"committed_date":"2020-02-28T20:14:27+08:00"
}
},
{
"name":"v0.11.5",
"commit":{
"committed_date":"2020-07-01T17:15:53+08:00"
}
},
{
"name":"v0.14.6",
"commit":{
"committed_date":"2020-08-02T18:20:22+08:00"
}
},
{
"name":"v0.9.7",
"commit":{
"committed_date":"2020-03-25T17:04:17+08:00"
}
}
]`
type Tags []Tag
func (t Tags) Len() int {
return len(t)
}
func (t Tags) Less(i, j int) bool {
ti := t[i].Commit.CommittedDate
tj := t[j].Commit.CommittedDate
return ti.Before(tj) // 按照Commit进行升序
}
func (t Tags) Swap(i, j int) {
t[i], t[j] = t[j], t[i]
}