前端之家收集整理的这篇文章主要介绍了
自动更新服务器代码片段,
前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
package main
import (
"fmt"
"io/IoUtil"
"log"
"path/filepath"
"sort"
"strconv"
"strings"
)
func main() {
list := Namesort(parse("server"))
sort.Sort(list)
fmt.Println(list)
}
func parse(dirpath string) []string {
dirname := filepath.Base(dirpath)
var l []string
list, err := IoUtil.ReadDir(dirpath)
if err != nil {
log.Println(err)
return l
}
for _, v := range list {
if strings.Contains(v.Name(), dirname) {
if toint(v.Name()) == -1 {
continue
}
l = append(l, v.Name())
}
}
return l
}
type Namesort []string
func (self Namesort) Swap(i, j int) {
self[i], self[j] = self[j], self[i]
}
func (self Namesort) Len() int {
return len(self)
}
func (self Namesort) Less(i, j int) bool {
ai := toint(self[i])
aj := toint(self[j])
if ai != -1 && aj != -1 {
return ai < aj
}
return false
}
func toint(str string) int {
list := strings.Split(str, "_")
if len(list) <= 1 {
return -1
}
n := list[len(list)-1]
num, err := strconv.Atoi(n)
if err != nil {
return -1
}
return num
}