Esempio n. 1
0
//postResponse is a boilerplate for HTTP POST responses.
func postResponse(c appengine.Context, target *url.URL, data io.Reader) (resp *http.Response, err error) {
	tr := urlfetch.Transport{Context: c}
	client := http.Client{Transport: &tr}
	resp, err = client.Post(target.String(), "application/json", data)
	if err != nil {
		return
	}
	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusCreated {
		msg := make(map[string]string)
		dec := json.NewDecoder(resp.Body)
		err = dec.Decode(&msg)
		if err != nil {
			Log.Debugf(c, "postResponse - %v", err)
		}
		resp.Body.Close()
		err = errors.New(resp.Status + ", Message: " + msg["error"])
	}
	return
}
func CallWithBasicAuth(c appengine.Context, address string, username string, password string, allowInvalidServerCertificate bool, method string, id interface{}, params []interface{}) (map[string]interface{}, error) {
	Log.Debugf(c, "gaehttpjsonrpc CallWithBasicAuth - %v", method)
	data, err := json.Marshal(map[string]interface{}{
		"method": method,
		"id":     id,
		"params": params,
	})
	if err != nil {
		Log.Infof(c, "Marshal: %v", err)
		return nil, err
	}

	req, err := http.NewRequest("POST", address, strings.NewReader(string(data)))
	if err != nil {
		Log.Infof(c, "Request: %v", err)
		return nil, err
	}
	req.SetBasicAuth(username, password)

	tr := &urlfetch.Transport{Context: c, Deadline: TimeoutDuration, AllowInvalidServerCertificate: allowInvalidServerCertificate}

	resp, err := tr.RoundTrip(req)
	if err != nil {
		Log.Infof(c, "Post: %v", err)
		return nil, err
	}
	defer resp.Body.Close()
	body, err := ioutil.ReadAll(resp.Body)
	if err != nil {
		Log.Infof(c, "ReadAll: %v", err)
		return nil, err
	}
	result := make(map[string]interface{})
	err = json.Unmarshal(body, &result)
	if err != nil {
		Log.Infof(c, "Unmarshal: %v", err)
		Log.Infof(c, "%s", body)
		return nil, err
	}
	//log.Println(result)
	return result, nil
}
Esempio n. 3
0
//putResponse is a boilerplate for HTTP PUT responses.
func putResponse(c appengine.Context, target *url.URL, data io.Reader) (resp *http.Response, err error) {
	req, err := http.NewRequest("PUT", target.String(), data)
	if err != nil {
		return
	}
	tr := urlfetch.Transport{Context: c}
	client := http.Client{Transport: &tr}
	resp, err = client.Do(req)
	if err != nil {
		return
	}
	if resp.StatusCode != http.StatusOK && resp.StatusCode != http.StatusNoContent {
		msg := make(map[string]string)
		dec := json.NewDecoder(resp.Body)
		err = dec.Decode(&msg)
		if err != nil {
			Log.Debugf(c, "putResponse - %v", err)
		}
		resp.Body.Close()
		err = errors.New(resp.Status + ", Message: " + msg["error"])
	}
	return
}