func()

in pkg/transport/http/http.go [145:193]


func (h *HTTP) request(requestor string, verb string, params url.Values) (*HTTPPartiallyDecodedResponse, error) {
	params.Set("requestor", requestor)
	u, err := url.Parse(h.Addr)
	if err != nil {
		return nil, fmt.Errorf("failed to parse server address '%s': %v", h.Addr, err)
	}
	if u.Scheme == "" {
		return nil, errors.New("server URL scheme not specified")
	}
	if u.Scheme != "http" && u.Scheme != "https" {
		return nil, fmt.Errorf("unsupported URL scheme '%s', please specify either http or https", u.Scheme)
	}
	u.Path += "/" + verb
	fmt.Fprintf(os.Stderr, "Requesting URL %s with requestor ID '%s'\n", u.String(), requestor)
	fmt.Fprintf(os.Stderr, "  with params:\n")
	for k, v := range params {
		fmt.Fprintf(os.Stderr, "    %s: %s\n", k, v)
	}
	fmt.Fprintf(os.Stderr, "\n")
	resp, err := http.PostForm(u.String(), params)
	if err != nil {
		return nil, fmt.Errorf("HTTP POST failed: %v", err)
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		return nil, fmt.Errorf("cannot read HTTP response: %v", err)
	}
	fmt.Fprintf(os.Stderr, "The server responded with status %s\n", resp.Status)

	var apiResp HTTPPartiallyDecodedResponse
	if resp.StatusCode == http.StatusOK {
		// the Data field of apiResp will result in a map[string]interface{}
		if err := json.Unmarshal(body, &apiResp); err != nil {
			return nil, fmt.Errorf("response is not a valid HTTP API response object: '%s': %v", body, err)
		}
		if err != nil {
			return nil, fmt.Errorf("cannot marshal HTTPAPIResponse: %v", err)
		}
	} else {
		var apiErr httplistener.HTTPAPIError
		if err := json.Unmarshal(body, &apiErr); err != nil {
			return nil, fmt.Errorf("response is not a valid HTTP API Error object: '%s': %v", body, err)
		}
		apiResp.Error = xjson.NewError(errors.New(apiErr.Msg))
	}

	return &apiResp, nil
}