go-resty / resty

Simple HTTP and REST client library for Go

Geek Repo:Geek Repo

Github PK Tool:Github PK Tool

How to handle response if a call to API returns 200 with struct A, or 201 with struct B?

arvenil opened this issue · comments

Hi,

I have a bit strange API to handle. POST to the endpoint usually returns 201 with created resource, but if resource already exists it will return 200 and an array with that specific resource. This means depending on status code I receive different payload - how this can be handled?

Hi.
Can you elaborate on the difficulty? From your description it sounds like a switch on the status code should do. Without more context I'd suggest something like:

	switch r.StatusCode() {
	case 200:
		return handleUpdatedCase(r)
	case 201:
		return handleCreatedCase(r)
	default:
		return handleError(r)
	}

If you are using automarshalling then you need to switch it off with SetDoNotParseResponse() then roll your own base on the status code per @lfrestrepog suggestion.

@arvenil Please go with combined suggestions from @alexhung & @lfrestrepog.

Also, in v3, I plan to improve response handling; Resty will possibly have out-of-the-box handling in this scenario.