Пример #1
0
func TestJsontools(t *testing.T) {

	var (
		json string
		blob []byte
	)

	json = `{
    "servers": [
        {
            "accessIPv4": "",
            "accessIPv6": "",
            "addresses": {
                "private": [
                    {
                        "addr": "192.168.0.3",
                        "version": 4
                    }
                ]
            },
            "created": "2012-09-07T16:56:37Z",
            "flavor": {
                "id": "1",
                "links": [
                    {
                        "href": "http://openstack.example.com/openstack/flavors/1",
                        "rel": "bookmark"
                    }
                ]
            },
            "hostId": "16d193736a5cfdb60c697ca27ad071d6126fa13baeb670fc9d10645e",
            "id": "05184ba3-00ba-4fbc-b7a2-03b62b884931",
            "image": {
                "id": "70a599e0-31e7-49b7-b260-868f441e862b",
                "links": [
                    {
                        "href": "http://openstack.example.com/openstack/images/70a599e0-31e7-49b7-b260-868f441e862b",
                        "rel": "bookmark"
                    }
                ]
            },
            "links": [
                {
                    "href": "http://openstack.example.com/v2/openstack/servers/05184ba3-00ba-4fbc-b7a2-03b62b884931",
                    "rel": "self"
                },
                {
                    "href": "http://openstack.example.com/openstack/servers/05184ba3-00ba-4fbc-b7a2-03b62b884931",
                    "rel": "bookmark"
                }
            ],
            "metadata": {
                "My Server Name": "Apache1"
            },
            "name": "new-server-test",
            "progress": 0,
            "status": "ACTIVE",
            "tenant_id": "openstack",
            "updated": "2012-09-07T16:56:37Z",
            "user_id": "fake"
        }
    ]
}`
	blob = []byte(json)
	jsontools.Json2map(blob[:], nil, true)

	fmt.Fprintf(os.Stderr, "======================== cache testing =======================\n")
	jc := jsontools.Mk_jsoncache()
	jc.Add_bytes([]byte(`{ "height": "5ft9in",`))
	blob = jc.Get_blob()
	if blob != nil {
		fmt.Fprintf(os.Stderr, " blob wasn't nil and should have been: (%s)\n", string(blob))
		t.Fail()
		os.Exit(1)
	}

	jc.Add_bytes([]byte(` "weight": "100lbs" } { "height", "6ft10in",`))
	blob = jc.Get_blob()
	if blob == nil {
		fmt.Fprintf(os.Stderr, " blob was nil and should NOT have been\n")
		t.Fail()
		os.Exit(1)
	}

	fmt.Fprintf(os.Stderr, "blob was returned as expected: (%s)\n]", string(blob))
	jc.Add_bytes([]byte(` "weight": "190lbs" } { "height", "7ft10in",`))
	blob = jc.Get_blob()
	fmt.Fprintf(os.Stderr, "blob was returned as expected: (%s)\n]", string(blob))

	fmt.Fprintf(os.Stderr, "======================== cache testing # 2 =======================\n")
	jc = jsontools.Mk_jsoncache() // 'clear'
	jc.Add_bytes([]byte(` { "ctype": "action_list", "actions": [ { "atype": "setqueues", "qdata": [ "qos106/fa:de:ad:7a:3a:72,E1res619_00001,2,20000000,20000000,200", "qos102/-128,res619_00001,2,20000000,20000000,200", "qos106/-128,Rres619_00001,2,10000000,10000000,200", "qos102/fa:de:ad:cc:48:f9,E0res619_00001,2,10000000,10000000,200" ], "hosts": [ "qos101", "qos102", "qos103", "qos104", "qos105", "qos106" ] } ] }`))
	blob = jc.Get_blob()
	fmt.Fprintf(os.Stderr, "blob was returned as expected: (%s)\n]", string(blob))

	fmt.Fprintf(os.Stderr, "======================== cache testing # 3 =======================\n")
	jc = jsontools.Mk_jsoncache() // 'clear'
	strs := strings.Split(json, "\n")
	for i := range strs {
		jc.Add_bytes([]byte(strs[i] + "\n"))

		if i < 14 {
			blob = jc.Get_blob()
			if blob != nil {
				fmt.Fprintf(os.Stderr, " blob was NOT nil and should have been: i=%d\n", i)
				t.Fail()
				os.Exit(1)
			}
		}
	}

	blob = jc.Get_blob()
	if blob == nil {
		fmt.Fprintf(os.Stderr, " blob was nil and should NOT have been\n")
		t.Fail()
		os.Exit(1)
	}

	fmt.Fprintf(os.Stderr, "blob was returned as expected: (%s)", string(blob))

}
Пример #2
0
func main() {
	var (
		version      string = "rjprt v1.4/16195"
		auth         *string
		err          error
		resp         *http.Response
		verbose      *bool
		root         *string
		raw_json     *bool
		needs_help   *bool
		target_url   *string
		dot_fmt      *bool
		look4        *string
		method       *string
		request_data *string
		req          *http.Request
	)

	needs_help = flag.Bool("?", false, "show usage")

	auth = flag.String("a", "", "authorisation token")
	dot_fmt = flag.Bool("d", false, "dotted named output")
	request_data = flag.String("D", "", "post data")
	raw_json = flag.Bool("j", false, "raw-json")
	show_headers := flag.Bool("h", false, "show http response headers")
	appl_json := flag.Bool("J", false, "data type is json")
	look4 = flag.String("l", "", "look4 string in hashtab")
	method = flag.String("m", "GET", "request method")
	root = flag.String("r", "", "top level root name")
	target_url = flag.String("t", "", "target url")
	tight_sec := flag.Bool("T", false, "tight security ON")
	verbose = flag.Bool("v", false, "verbose")
	flag.Parse() // actually parse the commandline

	input_type := "text" // type of data being sent in body
	if *appl_json {
		input_type = "application/json"
	}

	if *needs_help {
		usage(version)
		os.Exit(0)
	}

	if *look4 != "" { // -l imples -d
		*dot_fmt = true
	}

	if *target_url == "" {
		fmt.Fprintf(os.Stderr, "target url is missing from command line (use -t url)\n")
		os.Exit(1)
	}

	if *verbose {
		fmt.Fprintf(os.Stderr, "target=%s\n", *target_url)
	}

	trparms := &http.Transport{ // override default transport parms to skip the verify
		TLSClientConfig: &tls.Config{InsecureSkipVerify: !*tight_sec},
	}

	client := &http.Client{Transport: trparms} // default client except with our parms

	switch *method {
	case "GET", "get":
		req, err = http.NewRequest("GET", *target_url, nil)
		if err == nil {
			if auth != nil && *auth != "" {
				req.Header.Set("X-Auth-Tegu", *auth)
			}

			resp, err = client.Do(req)
		}

	case "POST", "post":
		if *request_data == "" {
			req, err = http.NewRequest("POST", *target_url, os.Stdin)
		} else {
			req, err = http.NewRequest("POST", *target_url, bytes.NewBufferString(*request_data))
		}

		if err == nil {
			req.Header.Set("Content-Type", input_type)
			if auth != nil && *auth != "" {
				req.Header.Set("X-Auth-Tegu", *auth)
			}

			resp, err = client.Do(req)
		}

	case "DELETE", "del", "delete":
		if *request_data == "" {
			req, err = http.NewRequest("DELETE", *target_url, os.Stdin)
		} else {
			req, err = http.NewRequest("DELETE", *target_url, bytes.NewBufferString(*request_data))
		}

		if err == nil {
			if auth != nil && *auth != "" {
				req.Header.Add("X-Auth-Tegu", *auth)
			}
			resp, err = client.Do(req)
		}

	default:
		fmt.Fprintf(os.Stderr, "%s method is not supported\n", *method)
		os.Exit(1)
	}

	if err != nil {
		fmt.Printf("%s request failed: %s\n", *method, err)
		os.Exit(1)
	} else {
		data, err := ioutil.ReadAll(resp.Body)
		if err != nil {
			fmt.Printf("read of data from url failed\n")
			os.Exit(1)
		}
		resp.Body.Close()

		if *show_headers {
			for k, v := range resp.Header {
				fmt.Printf("header: %s = %s\n", k, v)
			}
		}

		if data == nil {
			os.Exit(0) // maybe not what they were expecting, but nothing isn't an error
		}

		if *raw_json {
			fmt.Printf("%s\n", data)
			os.Exit(0)
		}

		if *dot_fmt {
			m, err := jsontools.Json2map(data, root, false) // build the map
			if err == nil {
				if *look4 != "" {
					result := m[*look4]
					if result != nil {
						switch result.(type) {
						case string:
							fmt.Printf("%s = %s\n", *look4, result.(string))

						case int:
							fmt.Printf("%s = %d\n", *look4, result.(int))

						case float64:
							fmt.Printf("%s = %.2f\n", *look4, result.(float64))

						default:
							fmt.Printf("found %s, but its in an unprintable format\n", *look4)
						}

					} else {
						fmt.Fprintf(os.Stderr, "didn't find: %s\n", *look4)
					}
				} else {
					jsontools.Print(m, *root, true)
				}
			} else {
				fmt.Fprintf(os.Stderr, "ERR: %s \n", err)
			}
		} else {
			_, err = jsontools.Json2blob(data, root, true) // normal hiarchy can be printed as it blobs, so ignore jif coming back
			if err != nil {                                // assume mirroring which doesn't put out json in all cases (boo)
				//fmt.Fprintf( os.Stderr, "ERR: %s \n", err );
				fmt.Fprintf(os.Stdout, "%s\n", data)
			}
		}
	}

	os.Exit(0)
}