Your code is incorrect. You call `w.Header().Set` after you already called `w.Write` (implicitly, in the `io.Copy`). You can't change headers after you already started writing the body.
My personal recommendation is to a) only write the body at the very end and b) ignore any errors returned from w.Write - it's too late to do anything about them (the headers are already written) and it's not even that unusual, as a client might close the connection in the middle of you writing the body. If reading from `src` (in your code) could create an error (for example, it does some encoding which could fail, or you're reading from a file), copy it to a *bytes.Buffer first - that way, you can first check that the encoding worked and then do the io.Copy(w, buf) without an error check. Reading from the buffer can't fail, and errors from writing to the ResponseWriter you can ignore. Or, if you don't want to buffer the result, live with the fact that the client might get a partial response. On Wed, Oct 6, 2021 at 3:04 PM RS <a0r2...@gmail.com> wrote: > Hi All, > we copy response body from a call into *responseWriter* w. > my question is: > a) if err!=nil, it is possible that w is also not nil? Or no: if err!=nil > then w is nil. > b) the following order is correct? > I would send response body (which is in *src* (resp.Body type > io.ReadCloser)) as xml content type with OK status. > And if error happens by io.Copy, then send a json body with status code > 599. > > > *w.Header().Set("Content-Type", "application/xml")* > > *_, err:=io.Copy(w,src) * > > *if err!=nil{* > *re := &res{ Message: "Error happened",}* > > > > *w.Header().Set("Content-Type", "application/json")w.WriteHeader(599) > //sample status codeerr = json.NewEncoder(w).Encode(re)* > *}//if* > > -- > You received this message because you are subscribed to the Google Groups > "golang-nuts" group. > To unsubscribe from this group and stop receiving emails from it, send an > email to golang-nuts+unsubscr...@googlegroups.com. > To view this discussion on the web visit > https://groups.google.com/d/msgid/golang-nuts/10d50e04-a328-4f54-a46d-947d4e2825d9n%40googlegroups.com > <https://groups.google.com/d/msgid/golang-nuts/10d50e04-a328-4f54-a46d-947d4e2825d9n%40googlegroups.com?utm_medium=email&utm_source=footer> > . > -- You received this message because you are subscribed to the Google Groups "golang-nuts" group. To unsubscribe from this group and stop receiving emails from it, send an email to golang-nuts+unsubscr...@googlegroups.com. To view this discussion on the web visit https://groups.google.com/d/msgid/golang-nuts/CAEkBMfG6UWUcPbtxpVzyKCSqQQP4z15sdHZa78ag5-df4fU5aA%40mail.gmail.com.