@@ -10,30 +10,53 @@ import (
1010 "github.com/xeipuuv/gojsonschema"
1111)
1212
13+ const usage = `Validate is used to check document with specified schema.
14+ You can use validate in following ways:
15+
16+ 1.specify document file as an argument
17+ validate <schema.json> <document.json>
18+
19+ 2.pass document content through a pipe
20+ cat <document.json> | validate <schema.json>
21+
22+ 3.input document content manually, ended with ctrl+d(or your self-defined EOF keys)
23+ validate <schema.json>
24+ [INPUT DOCUMENT CONTENT HERE]
25+ `
26+
1327func main () {
1428 nargs := len (os .Args [1 :])
1529 if nargs == 0 || nargs > 2 {
16- fmt .Printf ("ERROR: usage is: %s <schema.json> [<document.json>]\n " , os .Args [0 ])
30+ fmt .Printf ("ERROR: invalid arguments number\n \n %s\n " , usage )
31+ os .Exit (1 )
32+ }
33+
34+ if os .Args [1 ] == "help" ||
35+ os .Args [1 ] == "--help" ||
36+ os .Args [1 ] == "-h" {
37+ fmt .Printf ("%s\n " , usage )
1738 os .Exit (1 )
1839 }
1940
2041 schemaPath := os .Args [1 ]
2142 if ! strings .Contains (schemaPath , "://" ) {
22- schemaPath , err := filepath .Abs (schemaPath )
43+ var err error
44+ schemaPath , err = formatFilePath (schemaPath )
2345 if err != nil {
24- fmt .Println ( err )
46+ fmt .Printf ( "ERROR: invalid schema-file path: %s \n " , err )
2547 os .Exit (1 )
2648 }
2749 schemaPath = "file://" + schemaPath
2850 }
51+
2952 schemaLoader := gojsonschema .NewReferenceLoader (schemaPath )
3053
3154 var documentLoader gojsonschema.JSONLoader
3255
3356 if nargs > 1 {
34- documentPath , err := filepath . Abs (os .Args [2 ])
57+ documentPath , err := formatFilePath (os .Args [2 ])
3558 if err != nil {
36- fmt .Println ( err )
59+ fmt .Printf ( "ERROR: invalid document-file path: %s \n " , err )
3760 os .Exit (1 )
3861 }
3962 documentLoader = gojsonschema .NewReferenceLoader ("file://" + documentPath )
@@ -49,7 +72,8 @@ func main() {
4972
5073 result , err := gojsonschema .Validate (schemaLoader , documentLoader )
5174 if err != nil {
52- panic (err .Error ())
75+ fmt .Println (err )
76+ os .Exit (1 )
5377 }
5478
5579 if result .Valid () {
@@ -62,3 +86,15 @@ func main() {
6286 os .Exit (1 )
6387 }
6488}
89+
90+ func formatFilePath (path string ) (string , error ) {
91+ if _ , err := os .Stat (path ); err != nil {
92+ return "" , err
93+ }
94+
95+ absPath , err := filepath .Abs (path )
96+ if err != nil {
97+ return "" , err
98+ }
99+ return absPath , nil
100+ }
0 commit comments