1 files changed,
59 insertions(+),
4 deletions(-)
Author:
Oleksandr Smirnov
olexsmir@gmail.com
Committed at:
2025-11-26 22:31:35 +0200
Change ID:
lwpmvoswtrwxpmqpwzwrpvmxsspkxvvz
Parent:
25c3e78
M
cmd/json2go/main.go
@@ -1,9 +1,64 @@
package main -// todo: piped / sedin -// todo: passed as argument -// todo: read from file -// todo: set name of the type +import ( + "flag" + "fmt" + "io" + "os" + + "olexsmir.xyz/json2go" +) func main() { + typeName := flag.String("type", "AutoGenerated", "a name for generated type") + showHelp := flag.Bool("help", false, "show help") + flag.Parse() + + if *showHelp { + printHelp() + os.Exit(0) + } + + // get input + args := flag.Args() + + stat, err := os.Stdin.Stat() + if err != nil { + panic(err) + } + + isPiped := (stat.Mode() & os.ModeCharDevice) == 0 + + var input string + switch { + case len(args) > 0: + input = args[0] + case isPiped: + data, rerr := io.ReadAll(os.Stdin) + if rerr != nil { + panic(rerr) + } + input = string(data) + default: + printHelp() + os.Exit(1) + } + + transformer := json2go.NewTransformer() + type_, err := transformer.Transform(*typeName, input) + if err != nil { + panic(err) + } + + fmt.Println(type_) +} + +func printHelp() { + fmt.Println(` +Convert json to Go type annotations. + +Usage: + echo '{"json": "here"}' | json2go + echo '{"json": "here"}' | json2go -type=MyTypeName + json2go -type=MyTypeName '{"json": "here"}'`[1:]) }