Exemplo n.º 1
0
func (r *Request) do(method string, input interface{}, output interface{}) (resp *Response, err error) {
	var sawyerResp *sawyer.Response
	switch method {
	case sawyer.HeadMethod:
		sawyerResp = r.sawyerReq.Head()
	case sawyer.GetMethod:
		sawyerResp = r.sawyerReq.Get()
	case sawyer.PostMethod:
		mtype, _ := mediatype.Parse(defaultMediaType)
		r.sawyerReq.SetBody(mtype, input)
		sawyerResp = r.sawyerReq.Post()
	case sawyer.PutMethod:
		mtype, _ := mediatype.Parse(defaultMediaType)
		r.sawyerReq.SetBody(mtype, input)
		sawyerResp = r.sawyerReq.Put()
	case sawyer.PatchMethod:
		sawyerResp = r.sawyerReq.Patch()
	case sawyer.DeleteMethod:
		sawyerResp = r.sawyerReq.Delete()
	case sawyer.OptionsMethod:
		sawyerResp = r.sawyerReq.Options()
	}

	if sawyerResp.IsError() {
		err = sawyerResp.ResponseError
		return
	}

	if sawyerResp.IsApiError() {
		err = NewResponseError(sawyerResp)
		return
	}

	resp = &Response{Response: sawyerResp.Response, MediaType: sawyerResp.MediaType, MediaHeader: sawyerResp.MediaHeader}
	err = sawyerResp.Decode(output)

	return
}
Exemplo n.º 2
0
func TestSuccessfulPost(t *testing.T) {
	setup := Setup(t)
	defer setup.Teardown()

	mtype, err := mediatype.Parse("application/json")

	setup.Mux.HandleFunc("/users", func(w http.ResponseWriter, r *http.Request) {
		assert.Equal(t, "POST", r.Method)
		assert.Equal(t, mtype.String(), r.Header.Get("Content-Type"))

		user := &TestUser{}
		mtype.Decode(user, r.Body)
		assert.Equal(t, "sawyer", user.Login)

		head := w.Header()
		head.Set("Content-Type", "application/json")
		w.WriteHeader(http.StatusCreated)
		w.Write([]byte(`{"login": "******"}`))
	})

	client := setup.Client
	user := &TestUser{}

	req, err := client.NewRequest("users")
	assert.Equal(t, nil, err)

	user.Login = "******"
	req.SetBody(mtype, user)
	res := req.Post()
	assert.Equal(t, false, res.IsError())
	assert.Equal(t, false, res.IsApiError())
	assert.Equal(t, nil, res.Decode(user))

	assert.Equal(t, nil, err)
	assert.Equal(t, 201, res.StatusCode)
	assert.Equal(t, "sawyer2", user.Login)
	assert.Equal(t, true, res.BodyClosed)
}
Exemplo n.º 3
0
func mediaType(res *http.Response) (*mediatype.MediaType, error) {
	if ctype := res.Header.Get(ctypeHeader); len(ctype) > 0 {
		return mediatype.Parse(ctype)
	}
	return nil, nil
}
Exemplo n.º 4
0
func (r *Request) setBody(input interface{}) {
	mtype, _ := mediatype.Parse(defaultMediaType)
	r.sawyerReq.SetBody(mtype, input)
}