2021-02-22 17:27:13 +05:30
|
|
|
package proxy
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net/http"
|
|
|
|
"net/http/httputil"
|
|
|
|
"net/url"
|
|
|
|
"time"
|
|
|
|
|
2021-10-27 15:23:28 +05:30
|
|
|
"gitlab.com/gitlab-org/gitlab/workhorse/internal/helper"
|
2021-02-22 17:27:13 +05:30
|
|
|
)
|
|
|
|
|
|
|
|
var (
|
|
|
|
defaultTarget = helper.URLMustParse("http://localhost")
|
|
|
|
)
|
|
|
|
|
|
|
|
type Proxy struct {
|
|
|
|
Version string
|
|
|
|
reverseProxy *httputil.ReverseProxy
|
|
|
|
AllowResponseBuffering bool
|
2022-03-02 08:16:31 +05:30
|
|
|
customHeaders map[string]string
|
2021-02-22 17:27:13 +05:30
|
|
|
}
|
|
|
|
|
2022-03-02 08:16:31 +05:30
|
|
|
func WithCustomHeaders(customHeaders map[string]string) func(*Proxy) {
|
|
|
|
return func(proxy *Proxy) {
|
|
|
|
proxy.customHeaders = customHeaders
|
|
|
|
}
|
|
|
|
}
|
|
|
|
|
|
|
|
func NewProxy(myURL *url.URL, version string, roundTripper http.RoundTripper, options ...func(*Proxy)) *Proxy {
|
|
|
|
p := Proxy{Version: version, AllowResponseBuffering: true, customHeaders: make(map[string]string)}
|
2021-02-22 17:27:13 +05:30
|
|
|
|
|
|
|
if myURL == nil {
|
|
|
|
myURL = defaultTarget
|
|
|
|
}
|
|
|
|
|
|
|
|
u := *myURL // Make a copy of p.URL
|
|
|
|
u.Path = ""
|
|
|
|
p.reverseProxy = httputil.NewSingleHostReverseProxy(&u)
|
|
|
|
p.reverseProxy.Transport = roundTripper
|
2022-03-02 08:16:31 +05:30
|
|
|
|
|
|
|
for _, option := range options {
|
|
|
|
option(&p)
|
|
|
|
}
|
|
|
|
|
2021-02-22 17:27:13 +05:30
|
|
|
return &p
|
|
|
|
}
|
|
|
|
|
|
|
|
func (p *Proxy) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
|
|
|
// Clone request
|
|
|
|
req := *r
|
|
|
|
req.Header = helper.HeaderClone(r.Header)
|
|
|
|
|
|
|
|
// Set Workhorse version
|
|
|
|
req.Header.Set("Gitlab-Workhorse", p.Version)
|
|
|
|
req.Header.Set("Gitlab-Workhorse-Proxy-Start", fmt.Sprintf("%d", time.Now().UnixNano()))
|
|
|
|
|
2022-03-02 08:16:31 +05:30
|
|
|
for k, v := range p.customHeaders {
|
|
|
|
req.Header.Set(k, v)
|
|
|
|
}
|
|
|
|
|
2021-02-22 17:27:13 +05:30
|
|
|
if p.AllowResponseBuffering {
|
|
|
|
helper.AllowResponseBuffering(w)
|
|
|
|
}
|
|
|
|
|
|
|
|
// If the ultimate client disconnects when the response isn't fully written
|
|
|
|
// to them yet, httputil.ReverseProxy panics with a net/http.ErrAbortHandler
|
|
|
|
// error. We can catch and discard this to keep the error log clean
|
|
|
|
defer func() {
|
|
|
|
if err := recover(); err != nil {
|
|
|
|
if err != http.ErrAbortHandler {
|
|
|
|
panic(err)
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
|
|
|
p.reverseProxy.ServeHTTP(w, &req)
|
|
|
|
}
|