Пример #1
0
func TestGetRequest(t *testing.T) {
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		fmt.Fprintf(w, "ok")
	}))
	defer ts.Close()

	var err error

	_, err = greq.Get(ts.URL).Do()
	if err != nil {
		t.Error(err)
		return
	}

	if v, err := greq.Get(ts.URL).String(); err != nil {
		t.Error(err)
	} else if v != "ok" {
		t.Error(`response should be "ok"`)
	}

	if v, err := greq.Get(ts.URL).Bytes(); err != nil {
		t.Error(err)
	} else if string(v) != "ok" {
		t.Error(`response should be "ok"`)
	}
}
Пример #2
0
func main() {
	res, err := greq.Get("http://example.com/notfound.html").
		RequestHandler(greq.RetryBackoff(3, greq.NewBackOff())).
		ResponseHandler(func(res *http.Response, err error) error {
			if res != nil && res.StatusCode >= 400 && res.StatusCode < 500 {
				return errors.New("40X error")
			}
			return err
		}).Do()
	if err != nil {
		fmt.Println("error:", err.Error())
		return
	}
	body, _ := ioutil.ReadAll(res.Body)
	fmt.Println(string(body))
}
Пример #3
0
func TestJSONResponse(t *testing.T) {
	correctResponse := Response{1, "bluele"}
	ts := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
		resp, _ := json.Marshal(correctResponse)
		fmt.Fprint(w, string(resp))
	}))
	defer ts.Close()

	resp := &Response{}
	err := greq.Get(ts.URL).JSON(resp)
	if err != nil {
		t.Error(err)
		return
	}

	if resp.ID != correctResponse.ID || resp.Name != correctResponse.Name {
		t.Errorf("response should be %v", correctResponse)
	}
}