-
Notifications
You must be signed in to change notification settings - Fork 1
/
echo-json.go
204 lines (176 loc) · 3.86 KB
/
echo-json.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
package main
import (
"bytes"
"encoding/json"
"flag"
"fmt"
"os"
"strconv"
"strings"
)
type pairList map[string]interface{}
const (
typeString = "string"
typeInt = "int"
typeFloat = "float"
typeBool = "bool"
typeRaw = "raw"
)
var (
showVersion = flag.Bool("v", false, "show version information")
showHelp = flag.Bool("h", false, "show usage information")
)
// Version to display with -v.
// Set on build time with -ldflags "-X …"
var Version string
func main() {
flag.Usage = printHelp
flag.Parse()
if *showHelp {
printHelp()
os.Exit(0)
}
if *showVersion {
printVersion()
os.Exit(0)
}
b, err := args2JSON(flag.Args())
if err != nil {
switch err.(type) {
case *json.MarshalerError:
printError("Argument Error: A raw value (*:raw) contains invalid JSON\n")
default:
printError("%v\n", err)
}
}
fmt.Printf("%s\n", b)
}
func printVersion() {
fmt.Printf("echo-json\nVersion: %s\nMore info at https://github.com/filex/echo-json\n", version())
}
func printHelp() {
const usageTemplate = `
echo-json forms name/value pairs from its arguments and outputs a JSON object
Examples:
$ echo-json foo bar x y
{"foo":"bar","x":"y"}
$ echo-json b:bool true num:int 123
{"b": true, "num": 123}
Flags:
`
fmt.Println()
printVersion()
fmt.Println(usageTemplate)
flag.PrintDefaults()
}
func version() string {
if Version == "" {
Version = "development"
}
if Version[:1] == "v" {
return Version[1:]
}
return Version
}
func args2JSON(args []string) ([]byte, error) {
pairs, err := readPairs(args)
if err != nil {
return []byte(""), fmt.Errorf("Argument Error: %v", err)
}
var buf bytes.Buffer
enc := json.NewEncoder(&buf)
enc.SetEscapeHTML(false)
enc.SetIndent("", "")
if err = enc.Encode(pairs); err != nil {
return []byte(""), err
}
// Strip the newline that is added by Encode()
return buf.Bytes()[:buf.Len()-1], nil
}
func readPairs(args []string) (*pairList, error) {
num := len(args)
pairs := make(pairList, num/2+num%2)
var i int
var k, v string
isLast := func() bool {
return i >= num
}
useDefault := func() bool {
return isLast() || v == ""
}
for ; i < num; i++ {
k = args[i]
i++
v = ""
if !isLast() {
v = args[i]
}
// k can get a new name here
t, k := getType(k)
if k == "" {
return nil, fmt.Errorf("key (arg %v) may not be empty", i)
}
var tv interface{}
var err error
switch t {
case typeString:
tv = v
case typeInt:
if useDefault() {
tv = 0
} else if tv, err = strconv.ParseInt(v, 10, 64); err != nil {
return nil, fmt.Errorf("value \"%v\" for key \"%v\" is not an int: %v", v, k, err)
}
case typeFloat:
if useDefault() {
tv = 0.0
} else if tv, err = strconv.ParseFloat(v, 64); err != nil {
return nil, fmt.Errorf("value \"%v\" for key \"%v\" is not a float: %v", v, k, err)
}
case typeBool:
if useDefault() {
tv = false
} else if tv, err = strconv.ParseBool(v); err != nil {
return nil, fmt.Errorf("value \"%v\" for key \"%v\" is not a bool: %v", v, k, err)
}
case typeRaw:
if useDefault() {
tv = nil
} else {
tv = json.RawMessage([]byte(v))
}
}
pairs[k] = tv
}
return &pairs, nil
}
// getType checks for explicit given types and validates the type string.
func getType(key string) (string, string) {
if !strings.Contains(key, ":") {
return typeString, key
}
pos := strings.LastIndexByte(key, ':')
// key:type or namespaced:key:type
t := key[pos+1:]
k := key[:pos]
switch t {
case typeInt:
// age:int, type int, key "age"
return typeInt, k
case typeFloat:
return typeFloat, k
case typeBool:
return typeBool, k
case typeString:
return typeString, k
case typeRaw:
return typeRaw, k
default:
// foo:bar is string, key is "foo:bar"
return typeString, key // return _key_ here!
}
}
func printError(msg string, args ...interface{}) {
_, _ = fmt.Fprintf(os.Stderr, msg, args...)
os.Exit(1)
}