github.com/pyroscope-io/pyroscope@v0.37.3-0.20230725203016-5f6947968bd0/pkg/server/remoteread.go (about)

     1  package server
     2  
     3  import (
     4  	"net/http"
     5  	"net/http/httputil"
     6  	"net/url"
     7  
     8  	"github.com/pyroscope-io/pyroscope/pkg/config"
     9  	"github.com/sirupsen/logrus"
    10  )
    11  
    12  type RemoteReadHandler struct {
    13  	cfg   config.RemoteRead
    14  	proxy http.Handler
    15  	url   *url.URL
    16  }
    17  
    18  func (*Controller) remoteReadHandler(r config.RemoteRead) (http.HandlerFunc, error) {
    19  	f, err := NewRemoteReadHandler(r)
    20  	if err != nil {
    21  		return nil, err
    22  	}
    23  	return f.ServeHTTP, nil
    24  }
    25  
    26  func NewRemoteReadHandler(r config.RemoteRead) (*RemoteReadHandler, error) {
    27  	u, err := url.Parse(r.Address)
    28  	if err != nil {
    29  		return nil, err
    30  	}
    31  
    32  	p, err := newProxy(r.Address, r.AuthToken)
    33  	if err != nil {
    34  		return nil, err
    35  	}
    36  
    37  	return &RemoteReadHandler{
    38  		cfg:   r,
    39  		proxy: p,
    40  		url:   u,
    41  	}, nil
    42  }
    43  
    44  func (rh *RemoteReadHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
    45  	rh.proxy.ServeHTTP(w, r)
    46  }
    47  
    48  // newProxy takes target host and creates a reverse proxy
    49  func newProxy(targetAddress, token string) (http.Handler, error) {
    50  	target, err := url.Parse(targetAddress)
    51  	if err != nil {
    52  		return nil, err
    53  	}
    54  
    55  	p := httputil.NewSingleHostReverseProxy(target)
    56  	p.ErrorHandler = func(rw http.ResponseWriter, req *http.Request, err error) {
    57  		logrus.WithError(err).Error("error proxying request")
    58  	}
    59  
    60  	p.Director = func(r *http.Request) {
    61  		r.URL.Scheme = target.Scheme
    62  		r.URL.Host = target.Host
    63  		r.Host = target.Host
    64  		r.Header.Set("Authorization", "Bearer "+token)
    65  		r.Header.Set("Cookie", "")
    66  	}
    67  
    68  	f := func(w http.ResponseWriter, r *http.Request) {
    69  		p.ServeHTTP(w, r)
    70  	}
    71  	return http.HandlerFunc(f), nil
    72  }