1 Star 0 Fork 1

王布衣 / pkg

加入 Gitee
与超过 1200万 开发者一起发现、参与优秀开源项目,私有仓库也完全免费 :)
免费加入
克隆/下载
main.go 1.01 KB
一键复制 编辑 原始数据 按行查看 历史
王布衣 提交于 2023-12-29 07:11 . 新增: github.com/nxadm/tail v1.4.11
// Consume and unmarshall JSON.
//
// In this example JSON lines are added by createJSON in a tight loop.
// Each line is unmarshalled and a field printed.
// Exit with Ctrl+C.
package main
import (
"encoding/json"
"fmt"
"io/ioutil"
"os"
"strconv"
"gitee.com/quant1x/pkg/tools/tail"
)
type jsonStruct struct {
Counter string `json:"counter"`
}
func main() {
file, err := ioutil.TempFile(os.TempDir(), "")
if err != nil {
panic(err)
}
fmt.Println(file.Name())
defer file.Close()
defer os.Remove(file.Name())
t, err := tail.TailFile(file.Name(), tail.Config{Follow: true})
if err != nil {
panic(err)
}
go createJSON(file)
var js jsonStruct
for line := range t.Lines {
fmt.Printf("JSON: " + line.Text + "\n")
err := json.Unmarshal([]byte(line.Text), &js)
if err != nil {
panic(err)
}
fmt.Printf("JSON counter field: " + js.Counter + "\n")
}
}
func createJSON(file *os.File) {
var counter int
for {
file.WriteString("{ \"counter\": \"" + strconv.Itoa(counter) + "\"}\n")
counter++
}
}
1
https://gitee.com/quant1x/pkg.git
git@gitee.com:quant1x/pkg.git
quant1x
pkg
pkg
v0.2.7

搜索帮助