all repos

json2go @ e64121e986feae9f6224469c4d0ae8993ed7f22b

convert json to go type annotations

json2go/cmd/json2go/main.go (view raw)

Oleksandr Smirnov Oleksandr Smirnov
olexsmir@gmail.com
refactor: use an actual parser instead of reflection..., 2 months ago
1
package main
2
3
import (
4
	"flag"
5
	"fmt"
6
	"io"
7
	"os"
8
9
	"olexsmir.xyz/json2go"
10
)
11
12
func main() {
13
	typeName := flag.String("type", "AutoGenerated", "a name for generated type")
14
	noTags := flag.Bool("no-json-tags", false, "do not include json tags on struct fields")
15
	showHelp := flag.Bool("help", false, "show help")
16
	flag.Parse()
17
18
	if *showHelp {
19
		printHelp()
20
		os.Exit(0)
21
	}
22
23
	// get input
24
	args := flag.Args()
25
26
	stat, err := os.Stdin.Stat()
27
	if err != nil {
28
		fmt.Fprintf(os.Stderr, "Failed to get stdin stat: %v\n", err)
29
		os.Exit(1)
30
	}
31
32
	isPiped := (stat.Mode() & os.ModeCharDevice) == 0
33
34
	var input string
35
	switch {
36
	case len(args) > 0:
37
		input = args[0]
38
	case isPiped:
39
		data, rerr := io.ReadAll(os.Stdin)
40
		if rerr != nil {
41
			fmt.Fprintf(os.Stderr, "Failed to read piped input: %v\n", rerr)
42
			os.Exit(1)
43
		}
44
		input = string(data)
45
	default:
46
		printHelp()
47
		os.Exit(1)
48
	}
49
50
	type_, err := json2go.Transform(*typeName, input, !*noTags)
51
	if err != nil {
52
		fmt.Fprintf(os.Stderr, "Failed to transform json to type annotation: %v\n", err)
53
		os.Exit(1)
54
	}
55
56
	fmt.Println(type_)
57
}
58
59
func printHelp() {
60
	fmt.Println(`
61
Convert json to Go type annotations.
62
63
Usage:
64
	echo '{"json": "here"}' | json2go
65
	echo '{"json": "here"}' | json2go -type=MyTypeName
66
	json2go -type=MyTypeName '{"json": "here"}'
67
	json2go -no-json-tags '{"json": "here"}'
68
69
Flags:
70
	-type=NAME         Type name for root type (default: AutoGenerated)
71
	-no-json-tags      Omit json struct tags`[1:])
72
}