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 type HTTPError struct {
27 func (h HTTPError) Error() string {
31 // headers that shouldn't be forwarded when proxying. See
32 // https://developer.mozilla.org/en-US/docs/Web/HTTP/Headers
33 var dropHeaders = map[string]bool{
36 "Proxy-Authenticate": true,
37 "Proxy-Authorization": true,
40 "Transfer-Encoding": true, // *-Encoding headers interfer with Go's automatic compression/decompression
41 "Content-Encoding": true,
42 "Accept-Encoding": true,
46 type ResponseFilter func(*http.Response, error) (*http.Response, error)
48 // Forward a request to upstream service, and return response or error.
52 client *http.Client) (*http.Response, context.CancelFunc, error) {
54 // Copy headers from incoming request, then add/replace proxy
55 // headers like Via and X-Forwarded-For.
56 hdrOut := http.Header{}
57 for k, v := range reqIn.Header {
62 xff := reqIn.RemoteAddr
63 if xffIn := reqIn.Header.Get("X-Forwarded-For"); xffIn != "" {
64 xff = xffIn + "," + xff
66 hdrOut.Set("X-Forwarded-For", xff)
67 if hdrOut.Get("X-Forwarded-Proto") == "" {
68 hdrOut.Set("X-Forwarded-Proto", reqIn.URL.Scheme)
70 hdrOut.Add("Via", reqIn.Proto+" arvados-controller")
72 ctx := reqIn.Context()
73 var cancel context.CancelFunc
74 if p.RequestTimeout > 0 {
75 ctx, cancel = context.WithDeadline(ctx, time.Now().Add(time.Duration(p.RequestTimeout)))
78 reqOut := (&http.Request{
86 resp, err := client.Do(reqOut)
87 return resp, cancel, err
90 // Copy a response (or error) to the downstream client
91 func (p *proxy) ForwardResponse(w http.ResponseWriter, resp *http.Response, err error) (int64, error) {
93 if he, ok := err.(HTTPError); ok {
94 httpserver.Error(w, he.Message, he.Code)
96 httpserver.Error(w, err.Error(), http.StatusBadGateway)
101 defer resp.Body.Close()
102 for k, v := range resp.Header {
103 for _, v := range v {
107 w.WriteHeader(resp.StatusCode)
108 return io.Copy(w, resp.Body)