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, // *-Encoding headers interfer with Go's automatic compression/decompression
32 "Content-Encoding": true,
33 "Accept-Encoding": true,
37 type ResponseFilter func(*http.Response, error) (*http.Response, error)
39 func (p *proxy) Do(w http.ResponseWriter,
43 filter ResponseFilter) {
45 // Copy headers from incoming request, then add/replace proxy
46 // headers like Via and X-Forwarded-For.
47 hdrOut := http.Header{}
48 for k, v := range reqIn.Header {
53 xff := reqIn.RemoteAddr
54 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
55 xff = xffIn + "," + xff
57 hdrOut.Set("X-Forwarded-For", xff)
58 if hdrOut.Get("X-Forwarded-Proto") == "" {
59 hdrOut.Set("X-Forwarded-Proto", reqIn.URL.Scheme)
61 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
63 ctx := reqIn.Context()
64 if p.RequestTimeout > 0 {
65 var cancel context.CancelFunc
66 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(p.RequestTimeout)))
70 reqOut := (&http.Request{
78 resp, err := client.Do(reqOut)
79 if filter == nil && err != nil {
80 httpserver.Error(w, err.Error(), http.StatusBadGateway)
84 // make sure original response body gets closed
85 var originalBody io.ReadCloser
87 originalBody = resp.Body
88 if originalBody != nil {
89 defer originalBody.Close()
94 resp, err = filter(resp, err)
97 httpserver.Error(w, err.Error(), http.StatusBadGateway)
101 // filter() returned a nil response, this means suppress
102 // writing a response, for the case where there might
103 // be multiple response writers.
107 // the filter gave us a new response body, make sure that gets closed too.
108 if resp.Body != originalBody {
109 defer resp.Body.Close()
113 for k, v := range resp.Header {
114 for _, v := range v {
118 w.WriteHeader(resp.StatusCode)
119 n, err := io.Copy(w, resp.Body)
121 httpserver.Logger(reqIn).WithError(err).WithField("bytesCopied", n).Error("error copying response body")