[golang]寫了一個可以用 go 來寫腳本的工具:gosl
- 2019 年 10 月 11 日
- 筆記
轉自:https://golangtc.com/t/53cca103320b52060a000030
寫了一個可以用 go 來寫腳本的工具:gosl
代碼和使用說明可以看這裡: http://github.com/daviddengcn/gosl
Go Search 已經完全用 gosl 來啟動了。
相比 bash/Python 寫腳本的好處:
- 純 Go 語言,沒有新的學習成本
- 引入預先導入的 package 和預定義的內置函數,方便腳本書寫
- 可以無縫的和 Go 項目銜接,例如可以直接讀取數據和配置。
- 和 Go 有相同的執行效率,大大快過 Python
這裡貼一個簡單的例子:
#!/bin/gosl APPS := []string { "tocrawl", "crawler", "mergedocs", "indexer", } for { for _, app := range APPS { Printf("Running %s...n", app) Bash(app) } }
gosl
This is an application that can make you write script with the Go language.
It is NOT an interpreter but the pure Go. The preprocessor tranforms the script into a Go program, instantly compiles and runs. So it is almost same as the standard Go with the same efficiency.
Benefit
- Pure Go language. No need to learn a new script language.
- Pre-imported packages and pre-defined functions make it easy to code.
- Seamless integration with the Go project. E.g. can easily load configuration or data file from the Go project.
- Running efficiency same as Go, much faster than Python.
Example
- Simple
#!/bin/gosl import "encoding/json" toJson := func(lines []string) string { res, _ := json.Marshal(struct { Lines []string `json:"lines"` }{ Lines: lines, }) return string(res) } files := BashEval("ls -l %s", "/tmp/") Println(toJson(Split(files, "n")))
- Go Search is now operating with gosl. So you can find some good examples at: https://github.com/daviddengcn/gcse/tree/master/scripts
- go-diff also provides scripts in gosl: https://github.com/daviddengcn/go-diff/tree/master/scripts
Installation and Usage
Download and install the package
go get github.com/daviddengcn/gosl go install github.com/daviddengcn/gosl
(Optional) Link to /bin
sudo ln -s $GOPATH/bin/gosl /bin/gosl
If you don't want to do this, the interpreter line can be like this, assuming $GOPATH/bin
is in your $PATH
:
#!/usr/bin/env gosl
Run a script
If a script starts with the bash interpreter line: #!/bin/gosl
. You can run it like this
chmod a+x example.gs ./example.gs [params…]
Or you can explictly call gosl
to run it:
gosl example.gs [params…]
Pre-imported Packages
The following packages are pre-imported with .
, i.e. you can directly use the methods exported by them. No complain of the compiler if you don't use them.
fmt
, os
, strings
, strconv
, math
, time
, and github.com/daviddengcn/gosl/builtin
Frequently Used builtin
Functions
Method |
Description |
Example |
---|---|---|
S |
Convert anything to a string |
S(1234) == "123" |
I |
Convert anything to an int |
I("1234") == 1234 |
BashEval |
Similar to bash backtick substitution. |
lsstr := BashEval("ls -l") |
Exec |
Execute an command with arguments |
err, code := Exec("rm", "-rf" "tmp") |
Bash |
Execute a bash line |
err, code := Bash("rm -rf tmp") |
ScriptDir |
Returns the directory of the script |
file := ScriptDir() + "/" + fn |
More functions are defined in package daviddengcn/gosl/builtin/ (godoc)