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 downstream service, and return response or error.
49 func (p *proxy) ForwardRequest(
52 client *http.Client) (*http.Response, 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 if p.RequestTimeout > 0 {
74 ctx, _ = context.WithDeadline(ctx, time.Now().Add(time.Duration(p.RequestTimeout)))
77 reqOut := (&http.Request{
85 return client.Do(reqOut)
88 // Copy a response (or error) to the upstream client
89 func (p *proxy) ForwardResponse(w http.ResponseWriter, resp *http.Response, err error) (int64, error) {
91 if he, ok := err.(HTTPError); ok {
92 httpserver.Error(w, he.Message, he.Code)
94 httpserver.Error(w, err.Error(), http.StatusBadGateway)
99 defer resp.Body.Close()
100 for k, v := range resp.Header {
101 for _, v := range v {
105 w.WriteHeader(resp.StatusCode)
106 return io.Copy(w, resp.Body)