# go-utils **Repository Path**: dark.H/go-utils ## Basic Information - **Project Name**: go-utils - **Description**: golang tools for str slice - **Primary Language**: Go - **License**: AFL-3.0 - **Default Branch**: master - **Homepage**: None - **GVP Project**: No ## Statistics - **Stars**: 0 - **Forks**: 0 - **Created**: 2022-04-16 - **Last Updated**: 2022-05-05 ## Categories & Tags **Categories**: Uncategorized **Tags**: None ## README ## 项目描述 1. 基本目的 该库目的在于,提供一个强大的 基础调用库;将go的函数式统统变为链式调用 目前实现了 Str ,Dict[k,t] , List[T] 三种结构,并提供了一系列 类似 python 和 rust 的便捷操作。 ### 字符串常见操作 #### exmaple std 读取 ```golang package main import "gitee.com/dark.H/go-utils/s" func main() { s.Str("input some:").Println() s.Str("user name:").AsInput().Println("user name:") s.Str("password:").AsInput().Println("Password:") } ``` #### exmaple 字符串操作 提取字符串 ```golang package main import ( "fmt" "os" "gitee.com/dark.H/go-utils/s" ) var ( w = `this is a str test !!!!` w2 = `hell otis "sdsfd" asdfdsagdsa` w3 = "` asdfhaewg \" asdf 'fasfs ` asdfd" ) func main() { s.Str(" hello ").ANSIStyle(s.FgGreen, s.ANSI_STYLE_UNDERLINE).ANSISelected().Println() raw := s.Str("@ex.go").ParseFileContent() u, _ := os.UserHomeDir() fmt.Println(u) raw.Extract("\nimport", ")\n").MapWith(func(i int, item s.EStr) any { // return item.ANSIBold().ANSIUnderline().ANSIBlue() raw[item.Start:item.End].ANSIGreen().Println() return s.Str("{{IMPORT AREA}}").ANSISelected() }).Each(func(key s.Str, item2 any) { raw = raw.Replace(key.String(), item2.(s.Str).String()) // raw.StatusBar("show---") // time.Sleep(1 * time.Second) }) raw.ExtractQuote().Each(func(i int, item s.EStr) { raw[item.Start:item.End].ANSIYellow().Println() }) } ``` ```golang package main import ( "fmt" "gitee.com/dark.H/go-utils/s" ) func main() { raw := s.Str("@../extra_test/ex.go").ParseFileContent() // raw.ANSIGreen().Println() fmt.Println("--------- sub str test ------------") raw.SubStr(s.AFTER, "var").ExtractQuote().Each(func(i int, item s.EStr) { item.ANSIGreen().Println() }) raw.SubStr(s.FROM, "{", s.TO, s.LAST, "}").ANSIYellow().Println().ExtractQuote().Each(func(i int, item s.EStr) { item.ANSIGreen().Println() }) fmt.Println("------ edit test ---------------") raw.Edit(s.IN, "var (\n", ")", func(ex s.EStr) s.Str { return ex.Println().Insert("[test]", s.AFTER, "var (\n").Insert("[test-end]", ")") }).Println("[+ one]:").Edit(s.IN, "[test]", "[test-end]", func(e s.EStr) s.Str { return e.ANSIGreen().ANSIUnderline() }).Println("\n------------- sep ----------------- \n") } ``` #### exmaple 字符串-文件操作(打开/ls/验证存在) ```golang package main import ( "os/exec" "gitee.com/dark.H/go-utils/s" ) func main() { p := s.Str(os.Args[1]) p.FileList().Each(func(i int, item s.Str) { item.ANSIBlink().ANSIGreen().StatusBar("now in " + p.String()) time.Sleep(1 * time.Second) }) p2 := s.Str("asfsaf") p2.FileList() s.IfErrWillFatal() cmd := exec.Command("cmd.exe", "/c", "whoami") cmd.Output() } ``` ##### ini 配置文件的解析 [exmaple ini 配置文件的解析](https://gitee.com/dark.H/go-utils/blob/master/example/ini_decode/ini.go) ```golang package main import ( "fmt" "gitee.com/dark.H/go-utils/s" ) type S2 struct { Server string `ini:"server" default:"localhost:1080"` Name string `ini:"name" default:"no name"` Pwd string `ini:"pwd"` Port int `ini:"port" def:"80"` Can bool `ini:"can"` } func main1() { mp := s.Str("@ini.conf").ParseFileContent().ParseAsIniArg() c2 := new(S2) mp.DecodeAsStruct(c2) s.PrintlnStrcut(c2) } func main2() { c := &S2{ Server: "115.23.asf.assf", Pwd: "sdf", } s.ArgsFromINIStruct(c) s.PrintlnStrcut(c) if c.Can { fmt.Println(c.Name, c.Server, c.Port) } } ``` 或者 [exmaple ini 配置文件的解析2](https://gitee.com/dark.H/go-utils/blob/master/example/init_test/test.go) ```golang package main import ( "flag" "fmt" "log" "gitee.com/dark.H/go-utils/s" ) func main() { line := "" line2 := "" line3 := false flag.StringVar(&line, "s", "one", "helo its") flag.StringVar(&line2, "s2", "tw", "helo its") flag.BoolVar(&line3, "s3", false, "helo its") s.Args() fmt.Println("s2=", line2) fmt.Println("s3=", line3) fmt.Println("s=", line) c2 := s.Dict[s.Str, any]{ "hello": "asfasgadg", "we": "adsgadsgdddd", "ssss": "can you see", "this-num": 12521, "sub": s.Dict[s.Str, any]{ "sub-key": "key in second", "sub-num": 2, }, } res, err := c2.AsStr(`{key} = {val} `, "\n", "[{key}]\n") if err != nil { log.Fatal(err) } fmt.Println("\n\n[base]\n" + res) d := s.FromIni(s.Str("@./test.ini").ParseFileContent()) fmt.Println(d.Json()) } ``` ### ansi code 控制,包括了颜色, 进度条等功能: [exmaple sub str](https://gitee.com/dark.H/go-utils/blob/master/example/ansi_control/control.go) #### 进度条 ```golang package main import ( "fmt" "time" "gitee.com/dark.H/go-utils/s" ) func main() { raw := s.Str("@control.go").ParseFileContent() ls := raw.Split("\n") ls.Each(func(i int, item s.Str) { p := i * 100 / ls.Len() fmt.Println("line : ", item) s.ProgressShow(p, "show line:"+fmt.Sprint(i)) time.Sleep(1 * time.Second) }) } ``` ### 字节解析为 (自动将 Big5/utf16/gbk 转换为-> utf8 ) ```golang package main import ( "gitee.com/dark.H/go-utils/s" ) func main(){ someUtf16Bytes := []byte{......} str1,err := s.AutoDecode(someUtf16Bytes) str1.ANSIGreen().Println() } ``` ### 字符串作为cmd解析 (实现expect/完全交互) [exmaple shell/cmd](https://gitee.com/dark.H/go-utils/blob/master/example/cmd/cmdmain.go) ```golang package main import "gitee.com/dark.H/go-utils/s" func main() { // normal test // s.Str("whoami").AsCmd().Cd("..").Cd("~/Desktop").Exec("dir").Outputs().Each(func(i int, item s.Str) { // item.ANSIBlink().Println("[", i, "]: ") // }) // err test // s.Str("git -h").AsCmd().Output().ANSICyan().ANSIStrike().Println() // expect test s.Str("ls .").AsCmd("..").Cd("stdin_input").Exec("stdin_input.exe", s.CSTR_EXPECT, "name:$", s.CSTR_TYPE, "[test username]\n", s.CSTR_EXPECT, "password:$", s.CSTR_TYPE, "[test passwprd]\n", ).Output().ANSIBlink().Println() // interact test // s.Str("git add -A").AsCmd().Exec("git commit ", s.CSTR_INTERACT).Exec("git push origin master").Output().ANSIUnderline().ANSICyan().ANSIBold().Println() } ``` #### 字符串作为命令后台执行且,支持延迟执行 [exmaple shell/cmd](https://gitee.com/dark.H/go-utils/blob/master/example/delay_cmd/delay_main.go) ```golang package main import ( "fmt" "time" "gitee.com/dark.H/go-utils/s" ) func main() { now := time.Now() c := s.List[s.Str]{} c.Push("test").Push("test2").Each(func(i int, item s.Str) { item.Println() }) // s.Str("echo \"$(date) : $(whoami) \" > /tmp/test.log").AsCmd().Delay(10).Run() // 延时执行 s.Str("whoami > test.log").AsCmd().Delay(6).RunDaemon() // 延时执行删除自身的命令 s.Str("").AsCmd().DelSelf(7) fmt.Println("end : ", time.Since(now)) } ``` ### 字符串转 Bytes ,且支持流密钥加解密 [exmaple bytes/str encrypt](https://gitee.com/dark.H/go-utils/blob/master/example/encrypt_test/test3.go) ```golang package main import ( "fmt" "strconv" "time" "gitee.com/dark.H/go-utils/s" ) func main() { init := byte(0b11011100) out := byte(0) c := strconv.FormatInt(int64(init), 2) c3 := s.Str(c[0]).ANSIGreen().A(c[1:4]).A(s.Str(c[4:7]).ANSIGreen().A(s.Str(c[7]))) fmt.Println(" ---- test small m-sequence ----") fmt.Printf("%2d : %s | %d \n", -1, c3, out) for i := 0; i < 44; i++ { init = s.ByteMSeq(init) c := strconv.FormatInt(int64(init), 2) for len(c) < 8 { c = "0" + c } c3 := s.Str(c[0]).ANSIGreen().A(c[1:4]).A(s.Str(c[4:7]).ANSIGreen().A(s.Str(c[7]))) fmt.Printf("%2d : %s | %d \n", i, c3, out) } fmt.Println(" ---- test encyrpt and decrypted ----") test := s.Str(` Sonnet 18 --- by sharkspear Shall I compare thee to a summer's day? Thou art more lovely and more temperate: Rough winds do shake the darling buds of May, And summer's lease hath all too short a date: Sometime too hot the eye of heaven shines, And often is his gold complexion dimm'd; And every fair from fair sometime declines, By chance or nature's changing course untrimm'd But thy eternal summer shall not fade Nor lose possession of that fair thou owest; Nor shall Death brag thou wander'st in his shade, When in eternal lines to time thou growest: So long as men can breathe or eyes can see, So long lives this and this gives life to thee.`) fmt.Println(test.Words()) test = test.ANSIRandomBeautiful() println("raw :", test) println("\nlen :", len(test)) key := s.Bytes("key!") start := time.Now() enc := s.Bytes(test).HXor(key) used := time.Since(start) println("\nencryed :", enc) s.Str("used:" + used.String()).ANSIYellow().ANSIBold().Println() start = time.Now() dec := enc.HXor(key) used = time.Since(start) decs := dec.Decode() decs.Print("decypt: ") println("\nlen :", len(decs)) s.Str("used:" + used.String()).ANSIYellow().ANSIBold().Println() fmt.Println(" ---- test hex encrypt ----") raw := s.Str("C:\\windows\\system32\\cmd.exe").Println("raw:") en := raw.HXorHex(string(key)) en.Println() en.HXorHex(string(key)).Println("decry:") s.Str("288882f38f858987a96da29d94e2db6b936ab86ccc98bccdeff768").HXorHex("key!").Println() } ``` ## 扩展解析 os.Args 该库实现了golang的 flag <-> ini 文件 <-> Dict[k,t] <-> ini Str 等非常有用的参数和配置生成及转换 具体参见 ```golang package main import ( "fmt" "gitee.com/dark.H/go-utils/s" ) type S2 struct { Server string `ini:"server" default:"localhost:1080"` Name string `ini:"name" default:"no name"` Pwd string `ini:"pwd"` Port int `ini:"port" def:"80"` Can bool `ini:"can"` } func main1() { mp := s.Str("@ini.conf").ParseFileContent().ParseAsIniArg() c2 := new(S2) mp.DecodeAsStruct(c2) s.PrintlnStrcut(c2) } func main2() { c := &S2{ Server: "115.23.asf.assf", Pwd: "sdf", } s.ArgsFromINIStruct(c) s.PrintlnStrcut(c) if c.Can { fmt.Println(c.Name, c.Server, c.Port) } } ``` ## 结构 - s 包含了 Str , Dict,