1 // Copyright (C) The Arvados Authors. All rights reserved.
3 // SPDX-License-Identifier: AGPL-3.0
14 "git.curoverse.com/arvados.git/sdk/go/httpserver"
18 Name string // to use in Via header
19 RequestTimeout time.Duration
22 // headers that shouldn't be forwarded when proxying. See
23 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
24 var dropHeaders = map[string]bool{
27 "Proxy-Authenticate": true,
28 "Proxy-Authorization": true,
31 "Transfer-Encoding": true,
35 type ResponseFilter func(*http.Response) (*http.Response, error)
37 func (p *proxy) Do(w http.ResponseWriter,
41 filter ResponseFilter) {
43 // Copy headers from incoming request, then add/replace proxy
44 // headers like Via and X-Forwarded-For.
45 hdrOut := http.Header{}
46 for k, v := range reqIn.Header {
51 xff := reqIn.RemoteAddr
52 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
53 xff = xffIn + "," + xff
55 hdrOut.Set("X-Forwarded-For", xff)
56 if hdrOut.Get("X-Forwarded-Proto") == "" {
57 hdrOut.Set("X-Forwarded-Proto", reqIn.URL.Scheme)
59 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
61 ctx := reqIn.Context()
62 if p.RequestTimeout > 0 {
63 var cancel context.CancelFunc
64 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(p.RequestTimeout)))
68 reqOut := (&http.Request{
75 resp, err := client.Do(reqOut)
77 httpserver.Error(w, err.Error(), http.StatusBadGateway)
81 // make sure original response body gets closed
82 originalBody := resp.Body
83 defer originalBody.Close()
86 resp, err = filter(resp)
89 httpserver.Error(w, err.Error(), http.StatusBadGateway)
93 // filter() returned a nil response, this means suppress
94 // writing a response, for the case where there might
95 // be multiple response writers.
99 // the filter gave us a new response body, make sure that gets closed too.
100 if resp.Body != originalBody {
101 defer resp.Body.Close()
104 for k, v := range resp.Header {
105 for _, v := range v {
109 w.WriteHeader(resp.StatusCode)
110 n, err := io.Copy(w, resp.Body)
112 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")