2021年3月14日星期日

How to redirect multipart POST request to a second server in Golang?

I am trying to do the following.

|Upload file in HTML post file form|                |                ⌄  |Server A forwards the multipart request| |Server A receives response from Server B when Server B is done|                |                                     ^                ⌄                                     |  |Server B receives and stores the file from the forwarded multipart request|  

Processing the multipart request on Server A is straightforward, but when I try to process the forwarded request on Server B it fails with multipart: NextPart: EOF.

I am trying to create separate frontend/backend services. Frontend only handles UI related processing, while backend will actually do some processing on the file, hence the multipart request forwarding needed.

The forwarding code on Server A is as follows. The solution has been taken from here. https://stackoverflow.com/a/34725635/6569715

func forwardRequest(address string, path string, r *http.Request) (interface{}, error) {      body, err := ioutil.ReadAll(r.Body)      if err != nil {          return nil, err      }        r.Body = ioutil.NopCloser(bytes.NewReader(body))      proxyReq, err := http.NewRequest(r.Method, fmt.Sprintf("%s%s", address, path), bytes.NewReader(body))      if err != nil {          return nil, err      }        for header, values := range r.Header {          for _, value := range values {              proxyReq.Header.Add(header, value)          }      }        client := &http.Client{}      resp, err := client.Do(proxyReq)      if err != nil {          return nil, err      }      defer resp.Body.Close()      return resp, nil  }  

And the code on Server B to process the forwarded request:

func testMultiPart(w http.ResponseWriter, r *http.Request) {      if err := r.ParseMultipartForm(10 << 20); err != nil {          err = errors.Wrap(errors.WithStack(err), "Backend: Failed to parse form")          w.WriteHeader(http.StatusInternalServerError)          fmt.Fprint(w, fmt.Sprintf("{\"error\":\"%s\"}", err.Error())          return      }  }  

Any help is appreciated.

https://stackoverflow.com/questions/66591844/how-to-redirect-multipart-post-request-to-a-second-server-in-golang March 12, 2021 at 07:03AM

没有评论:

发表评论